且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

日历的日期对象 [Java]

更新时间:2023-09-19 23:28:52

你可以做的是创建一个 GregorianCalendar 的实例,然后将 Date 设置为开始时间:

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);

但是,另一种方法是根本不使用 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.