在 date.gettime() 中获得负值

Getting negative value in date.gettime()

遇到一个问题,我试图将字符串值解析为日期,当我尝试执行 date.getTime() 时,我得到了负值。

这是我正在解析的字符串“01:00:07”。 这是我得到的日期对象中的值 "Thu Jan 01 01:00:07 GMT+05:30 1970"。 仍在 getTime() 中,我得到负值“-16193000”

实现代码:

long sum = 0;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss");// I have also tried "HH:mm:ss" format. it gives same result
    Date date = simpleDateFormat.parse(duration);//duration is "01:00:07"
    sum= date.getTime();

simpleDateFormat .setTimeZone(TimeZone.getTimeZone("GMT")); 你必须添加你的时区

问题是时区偏移。使用:

long sum = 0;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss");// I have also tried "HH:mm:ss" format. it gives same result
Date date = null;//duration is "01:00:07"
try {
    date = simpleDateFormat.parse("01:00:07");
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    sum= cal.getTimeInMillis() + (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET));
    System.out.println("Date =" + date);
    System.out.println("sum =" + sum);
} catch (ParseException e) {
    e.printStackTrace();
}

问题是TimeZone。您将通过提供 TimeZone

获得正确的时间
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

java.time

    String durationString = "01:00:07";
    durationString = durationString
            .replaceFirst("(\d{2}):(\d{2}):(\d{2})", "PTHMS");
    Duration dur = Duration.parse(durationString);
    System.out.println(dur);

A Duration 输出这个奇数字符串:

PT1H7S

读作:1小时7秒的时间段

该字符串采用标准 ISO 8601 格式。 A Duration 只能解析标准格式。所以我正在使用 String.replaceFirst 将您的字符串转换为它。

让我猜猜,你需要总结持续时间?有一个 plus 方法:

    Duration sum = Duration.ZERO;
    sum = sum.plus(dur);

也有转换为秒或毫秒的方法。

不要在持续时间内使用日期时间 class。这会导致混乱和错误。

如果你绝对不想要外部依赖(直到你移动到 API 级别 26),手动将你的字符串解析为秒并用 int 表示它们。用您自己的自定义 class 包装它。

问题:我可以在 Android 上使用 java.time 吗?

是的,java.time 在新旧 Android 设备上都能很好地工作。它只需要至少 Java 6.

  • 在 Java 8 和更高版本以及较新的 Android 设备(从 API 级别 26)中内置现代 API。
  • 在 Java 6 和 7 中获取 ThreeTen Backport,新 classes 的 backport(ThreeTen 用于 JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 使用 ThreeTen Backport 的 Android 版本。它叫做 ThreeTenABP。并确保使用子包从 org.threeten.bp 导入日期和时间 classes。

链接