Date object to Calendar [Java]

后端 未结 7 1959
花落未央
花落未央 2020-12-02 19:31

I have a class Movie in it i have a start Date, a duration and a stop Date. Start and stop Date are Date Objects (private Date startDate ...) (It\'s an assignment so i cant

7条回答
  •  情书的邮戳
    2020-12-02 20:10

    What you could do is creating an instance of a GregorianCalendar and then set the Date as a start time:

    Date date;
    Calendar myCal = new GregorianCalendar();
    myCal.setTime(date);
    

    However, another approach is to not use Date at all. You could use an approach like this:

    private Calendar startTime;
    private long duration;
    private long startNanos;   //Nano-second precision, could be less precise
    ...
    this.startTime = Calendar.getInstance();
    this.duration = 0;
    this.startNanos = System.nanoTime();
    
    public void setEndTime() {
            this.duration = System.nanoTime() - this.startNanos;
    }
    
    public Calendar getStartTime() {
            return this.startTime;
    }
    
    public long getDuration() {
            return this.duration;
    }
    

    In this way you can access both the start time and get the duration from start to stop. The precision is up to you of course.

提交回复
热议问题