java - 安卓Java : Difference between current time and specific time in future is calculated wrong

标签 java android date date-difference

我需要当前时间和 future 特定时间之间的差异,以便我可以将倒数计时器作为参数传递。我有这个操作的功能,但它计算错误。 这是我计算差异的函数

   public Date RetriveLeftTime(Date incomingTime) {

    DateFormat milisFormat = new SimpleDateFormat("HH:mm:ss");
    Date moment = Calendar.getInstance().getTime();
    milisFormat.format(moment);
    Date configuredTime = ConfigureTime(incomingTime);
    milisFormat.format(configuredTime);
    long leftTime =configuredTime.getTime()-moment.getTime();

    Date result = new Date(leftTime);
    result = ConfigureTime(result);

    Log.d("Result",result.toString());

    return result;

}

用于配置日期详细信息的 ConfigureTime() 函数

public Date ConfigureTime(Date date){

    Calendar today = Calendar.getInstance();
    int date = today.get(Calendar.DATE);
    int year = today.get(Calendar.YEAR);
    int day = today.get(Calendar.DAY_OF_WEEK);
    int month = today.get(Calendar.MONTH);
    int zone = today.get(Calendar.ZONE_OFFSET);

    Calendar time = Calendar.getInstance();
    time.setTime(date);

    time.set(Calendar.YEAR, year);
    time.set(Calendar.MONTH, month);
    time.set(Calendar.DAY_OF_WEEK, day);
    time.set(Calendar.DATE, date);
    time.set(Calendar.ZONE_OFFSET,zone);

    Log.d("ConfigureTime()",time.getTime().toString());
    Log.d("Current Time",today.getTime().toString());

    return time.getTime();
}

我看过关于这个问题的类似帖子。我检查并配置了我所有的时间规范,如时区、日期、年份,但仍然得到错误的结果。我不明白为什么会这样。也许我的代码做错了我不知道。我做错了什么? 大多数人建议使用 joda time,但我想切换 joda time 有点过头了。在切换到 joda time 之前有解决方案吗?

最佳答案

tl;dr

Duration
.between(
    Instant.now() ,
    myJavaUtilDate.toInstant()
)
.toMillis()

java.time

您使用的糟糕类在多年前被 JSR 310 中定义的现代 java.time 类所取代。切勿使用 Calendar日期SimpleDateFormat

即时

如果您收到一个 java.util.Date 对象,请立即转换为一个 Instant 对象。使用添加到旧类的新转换方法。

Instant then = myJavaUtilDate.toInstant() ;

Instant 表示“UTC 时间”中的时刻,偏移量为零小时-分钟-秒。

以 UTC 格式捕捉当前时刻。

Instant now = Instant.now() ;

计算要耗时。

Duration d = Duration.between( now , then ) ;

验证您的目标时刻确实在未来。

if( d.isNegative() ) { … deal with faulty input … }

通常最好传递一个 Duration 对象,而不是单纯的以毫秒或纳秒为单位的整数。但如果需要,您可以从 Duration 对象中提取计数。

long milliseconds = d.toMillis() ;

请注意,通过使用 UTC,我们不需要处理任何时区问题。

安卓

如果使用 Android 26+,此功能是内置的。对于早期的 Android,最新的工具通过“API 脱糖”带来了大部分功能。

关于java - 安卓Java : Difference between current time and specific time in future is calculated wrong,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70413391/

相关文章:

用于输入日期的 Java JFormattedTextField

java - 垃圾收集器不工作?

java - 根据数据动态创建 View

Java 'CheckBox Node Tree Sample' DefaultMutableNode 没有任何监听器?

java - View 在可见时窃取辅助功能焦点

android - getExtra from Intent 从一个 pendingIntent 启动

excel - 计算某个日期出现的次数并绘制图表

sql - 如何找到两个日期之间的持续时间

java - 查找 AttributeValue 的数据类型

java - 即使在 vm args 中使用 XstartOnFirstThread,线程访问也无效