TimeDelta java?

梦想与她 提交于 2019-12-04 07:04:53

问题


I am trying to convert code from Python to Java. I need to rewrite the timeDelta function in Java. Here is the code in Python:

def timeDate(date):
    return (timedelta(seconds=date * 3600 % 86400))

Does anyone have any idea on how to make a function that acts the same?


回答1:


    double hours = 21.37865107050986;
    long nanos = Math.round(hours * TimeUnit.HOURS.toNanos(1));
    Duration d = Duration.ofNanos(nanos);
    // Delete any whole days
    d = d.minusDays(d.toDays());
    System.out.println(d);

This prints:

PT21H22M43.143853836S

Which means: a duration of 21 hours 22 minutes 43.143853836 seconds.

Assumptions: I understand that you want a duration (the docs you link to say “A timedelta object represents a duration”). I have taken date to be a floating-point number of hours, and your modulo operation lead me to believe that you want the duration modulo 1 day (so 26 hours should come out as a duration of 2 hours).

The Duration class in Java is for durations, hence is the one that you should use. It doesn’t accept a floating point number for creation, so I converted your hours so nanoseconds and rounded to whole number. For the conversion I multiplied by the number of nanoseconds in 1 hour, which I got from the call to TimeUnit (this gives clearer and less error-prone code than multiplying out ourselves).

The code above will tacitly give incorrect results for numerically large numbers of hours, so you should check the range before using it. Up to 2 500 000 hours (100 000 days or nearly 300 years) you should be safe.

Please note: if date was a time of day and not a duration, it’s a completely different story. In this case you should use LocalTime in Java. It’s exactly for a time of day (without date and without time zone).

    nanos = nanos % TimeUnit.DAYS.toNanos(1);
    LocalTime timeOfDay = LocalTime.ofNanoOfDay(nanos);
    System.out.println(timeOfDay);

21:22:43.143853836

Link: Documentation of the Duration class




回答2:


As far as I know, Java doesn't have a built in DeltaTime function. However you can easily make your own.long startTime; long delta; public void deltaTime(){ long currentTime = System.currentTimeMillis(); delta = currentTime - startTime;}

Whenever you want to start your DeltaTime timer, you just do time = System.currentTimeMillis;. This way, the variable "delta" is the amount of time between when you started the DeltaTime timer and when you end it using ClassNameHere.deltaTime();.




回答3:


private static LocalTime timeDate(double d) { //converts into a local time return LocalTime.ofSecondOfDay((long)(d*3600%86400));
}
Input (d): 36.243356711275794

Output: 21:22:43



来源:https://stackoverflow.com/questions/51526726/timedelta-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!