有 Java 编程相关的问题?

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

java在Android中使用“Calendar”指定日期时间范围

社会各界,

我目前正在做我的新项目,我是Java和Android Studio的新手。 我已经用两个Calendar变量编写了自己的Entry类。 是否有一种更短更干净的方法来创建一个新的Entry对象,如下面的代码所示

//MainActivity.java    
//....
private ArrayList<Entry> initEntrys() {
        ArrayList<Entry> list = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();

        Calendar mStartDate = calendar;
        Calendar mEndDate = calendar;
        mStartDate.set(2019, 12, 20, 7, 0);
        mEndDate.set(2019, 12, 20, 10, 0);
        list.add(new Entry(mStartDate, mEndDate));

        return list;
    }

任何帮助都将不胜感激。:)


共 (2) 个答案

  1. # 1 楼答案

    我将使用^{}类覆盖一个时间分区日期来完成Answer by Basil Bourque

    我在示例中使用了UTC时区,但您可以使用所需的适当时区进行自定义

    LocalDateTime ldtStart = LocalDateTime.of( 2019 , 12 , 20 , 7 , 0 , 0 , 0 ) ;
    ZonedDateTime ldtZonedStart = ldtStart.atZone(ZoneId.systemDefault());
    ZonedDateTime utcZonedStart = ldtZonedStart.withZoneSameInstant(ZoneOffset.UTC);
    
    
    LocalDateTime ldtStop = LocalDateTime.of( 2019 , 12 , 20 , 10 , 0 , 0 , 0 ) ;
    ZonedDateTime ldtStopZoned = ldtStop.atZone(ZoneId.systemDefault());
    ZonedDateTime utcZonedStop = ldtStopZoned.withZoneSameInstant(ZoneOffset.UTC);
    
  2. # 2 楼答案

    tl;博士

    切勿使用Calendar之类的旧日期时间类仅使用java。时间课程

    对于包含一天中某个时间但缺少时区或UTC偏移量的日期,请使用^{}

    LocalDateTime.of( 2019 , 12 , 20 , 7 , 0 )  // year, month, day , hour , minute. 
    

    避免遗留日期时间类

    永远不要使用Calendar那个类很糟糕,设计有缺陷。多年前,它被现代的爪哇取代。JSR 310中定义的时间

    爪哇。时间

    与遗留类相比,java。时间类是设计不变的,因此是线程安全的

    我们实例化java,而不是将构造函数与new一起使用。通过调用静态工厂方法(如^{})来调用time对象

    一刻也不

    如果您有意识地在没有time zoneoffset-from-UTC上下文的情况下工作,请使用^{}对象

    LocalDateTime start = LocalDateTime.of( 2019 , 12 , 20 , 7 , 0 ) ;  // Passing year, month, day , hour , minute. The second and fractional-second both default to zero.
    LocalDateTime stop = LocalDateTime.of( 2019 , 12 , 20 , 10 , 0 ) ;
    

    瞬间

    如果您试图表示时间线上的时刻、特定点,那么^{}就是错误的

    对于跟踪时刻,您需要时区的上下文(或者更可取的是,与UTC的偏移)。为此,请使用^{},如Answer by CrackerGen中所示


    Table of all date-time types in Java, both modern and legacy


    关于java。时间

    java.time框架内置于Java8和更高版本中。这些类取代了麻烦的旧legacy日期时间类,如^{}^{}、&^{}

    要了解更多信息,请参阅Oracle Tutorial。并搜索堆栈溢出以获得许多示例和解释。规范是JSR 310

    现在位于maintenance modeJoda-Time项目建议迁移到java.time

    您可以交换java。时间对象直接与数据库连接。使用符合JDBC 4.2或更高版本的JDBC driver。不需要字符串,也不需要java.sql.*

    在哪里可以获得java。时间课

    Table of which java.time library to use with which version of Java or Android