有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在kotlin中使用时间的最佳方式是什么?

我正在使用Kotlin开发一个Android应用程序,我希望实现以下目标:

  1. 让用户选择从当前时间到接下来24小时的警报时间(hh:mm) e、 g.在16:00,用户希望在明天15:00发出警报
  2. 一旦用户设置了警报,我想显示激活警报之前的剩余时间(hh:mm) e、 g.显示一个小对话框,文本为:3小时:15分钟

在Kotlin中处理时间操作(将当前时间减去警报时间)的最佳方法是什么


共 (2) 个答案

  1. # 1 楼答案

    根据Basil Bourque的说法,以下是他提出的(Java)转换成Kotlin的代码,以防有人感兴趣

    
    // Credit to Basil Bourque Answer
    // https://stackoverflow.com/questions/59846004/what-is-the-best-way-to-operate-with-time-in-kotlin/59846550#59846550
    
    lateinit var zdt: ZonedDateTime
    val targetLocaltime = LocalTime.of(21, 0)
    val z = ZoneId.of("Europe/Madrid")
    val now = ZonedDateTime.now(z)
    val runToday = now.toLocalTime().isBefore(targetLocaltime)
    
    zdt = if (runToday){
        now.with(targetLocaltime)
    }
    else{
        now.toLocalDate().plusDays(1).atStartOfDay(z).with(targetLocaltime)
    }
    val eta = Duration.between(now.toInstant(), zdt.toInstant()).toMinutes()
    if(eta > 60){
        val hours = eta / 60
        val minutes = eta % 60
        print("$hours:$minutes remaining")
    }
    else{
        print("$eta minutes remaining")
    }
    
  2. # 2 楼答案

    关于堆栈溢出,您的所有问题都已被多次询问和回答。所以我会很简短。搜索以了解更多信息

    只使用java。时间类,而不是像DateCalendar这样糟糕的遗留类

    对于26岁之前的Android,请参阅ThreeTen Backport库及其Android特定的包装器ThreeTenABP

    LocalTime表示一天中的某个时间

    LocalTime targetLocalTime = LocalTime.of( 15 , 0 ) ;
    

    获取当前时刻。需要时区。像CST这样的2-4个字母的代码不是实时时区。真正的区域被命名为Continent/Region

    ZoneId z = ZoneId.of( "America/Montreal" ) ;
    ZonedDateTime now = ZonedDateTime.now( z ) ;
    

    比较时间部分。提取一个LocalTime进行比较

    Boolean runToday = now.toLocalTime().isBefore( targetLocalTime ) ;
    

    确定下一个报警时间

    ZonedDateTime zdt = now.with( targetLocalTime ) ; 
    

    或者如果第二天需要,明天

    ZonedDateTime zdt = now.toLocalDate().plusDays( 1 ).atStartOfDay( z ).with( targetLocalTime ) ;
    

    计算经过的时间。通过提取Instant来调整UTC

    Duration d = Duration.between( now.toInstant() , zdt.toInstant() ) ;
    

    生成标准ISO 8601格式的字符串

    String output = d.toString() ;
    

    或者通过调用Duration::to…Part方法生成另一种格式的字符串

    至于触发警报,在纯Java中使用执行器框架,特别是ScheduledExecutorService。这个框架使运行后台线程在某个时刻触发任务Runnable变得简单。几乎可以肯定的是,CPU上的垃圾收集或线程/进程调度可能会出现轻微延迟,但对于商业应用程序来说已经足够了(对于NASA来说还不够好)

    安卓还可能提供一些报警设置功能。(我不知道)

    永远不要从后台线程访问或操作用户界面。使用Android提供的任何钩子从另一个线程更新UI,例如刷新UI小部件或显示通知