val calendar = Calendar.getInstance和val date = Date返回错误的时间

如何解决val calendar = Calendar.getInstance和val date = Date返回错误的时间

我编写了两个函数来获取start timeend time。结束时间始终是当前时间,开始时间始终是当前时间减去2秒。

这是功能代码。

private fun getStartDateTime(): String {
    val dateFormat = SimpleDateFormat(Constants.SERVER_DATE_FORMAT,Locale.getDefault())
    val calendar = Calendar.getInstance() 
    calendar.add(Calendar.SECOND,-2)
    return dateFormat.format(calendar.time)
}

private fun getEndDateTime(): String {
    val dateFormat = SimpleDateFormat(Constants.SERVER_DATE_FORMAT,Locale.getDefault())
    val date = Date()
    return dateFormat.format(date)
}

在大多数设备中,它都可以正常工作,但是当我在 Oneplus 6 中对其进行测试时,它在调用此函数的同时开始给我时间。请查看以下本地数据库表的屏幕快照。

enter image description here

问题: 这些功能每2秒调用一次。因此开始时间和结束时间应该是唯一的。我为什么没有得到唯一的start timeend time的任何理由?

修改

在创建调用之类的新对象时会调用这些函数

val abc = ABC(xxx,xxx,getStartDateTime(),getEndDateTime())

解决方法

您的方法有缺陷。

由于开始日期时间和结束日期时间是相互依赖的,因此您应该从另一个开始。您的方法存在的问题是,您要从它们的计算时间中得出开始日期时间和结束日期时间,即您有两个变量(开始日期时间和结束日期的计算时间-时间),而不是一个。

下面是执行此操作的Java代码,希望您可以将其转换为Kotlin:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        // Test
        System.out.println(getStartDateTime());
        System.out.println(getEndDateTime());
    }

    /**
     * 
     * Derives start date-time from end date-time
     * 
     * @throws ParseException
     */
    private static String getStartDateTime() throws ParseException {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
        Date date = dateFormat.parse(getEndDateTime());// Get end date-time
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.SECOND,-2);
        return dateFormat.format(calendar.getTime());
    }

    private static String getEndDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);
    }
}

示例运行的输出:

2020-09-28 11:26:58
2020-09-28 11:27:00

一条建议:

我建议您从过时且容易出错的java.util日期时间API和SimpleDateFormat切换到modern java.time日期时间API和相应的格式化API (软件包java.time.format)。从 Trail: Date Time 了解有关现代日期时间API的更多信息。如果您的Android API级别仍不符合Java-8,请检查Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

使用现代的日期时间API:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getStartDateTime());
        System.out.println(getEndDateTime());
    }

    /**
     * 
     * Derives start date-time from end date-time
     * 
     */
    private static String getStartDateTime() {
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss",Locale.getDefault());
        LocalDateTime ldt = LocalDateTime.parse(getEndDateTime(),dateFormat);// Get end date-time
        return dateFormat.format(ldt.minusSeconds(2));
    }

    private static String getEndDateTime() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss",Locale.getDefault()));
    }
}
,

这是猜测。一些可能的解释包括:

  • (不太可能。)设备上的时钟已停止。
  • (不太可能。)该设备上的Calendar.getInstance()Date()的实现会过多地缓存,并从陈旧的缓存中获得价值。
  • 计划程序无法在该设备上运行,并且比每2秒更频繁地调用一次函数。作为一种可能的变体,正在运行多个调度程序,每个调度程序每2秒调用一次。
  • 由于某些错误,您的对象多次使用不同的ID插入数据库。

我们没有任何信息可以使我们更加接近。就像chrylis -cautiouslyoptimistic-在评论中说的那样,您可以从函数中进行一些日志记录,以查看在程序运行期间它真正被调用了多少次。 Aslo如何将1332个条目与预期数量进行比较?

顺便说一句,如果可以的话,最好使用现代Java日期和时间API java.time,如其他答案的后半部分所述。如果问题确实是过时的缓存,那么也很有可能避免该问题。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-