How can I convert the result of System.nanoTime to a date in Java?

前端 未结 3 680
天涯浪人
天涯浪人 2021-01-02 07:59

I want to convert the result of System.nanoTime() to a date.

public void tempBan(Player p, Player banner, int timeInSeconds){
    Long timeInNano = (long) (t         


        
3条回答
  •  孤城傲影
    2021-01-02 08:32

    You can convert it into system time using the below code

    public static long convertToUnixMs(final long timeMs) {
        final long refMonoMs = monoTimeMs();
        final long refUnixMx = System.currentTimeMillis();
    
        return refUnixMx + (timeMs - refMonoMs);
    }
    public static long monoTimeMs() {
            return System.nanoTime() / 1000000;
        }
    

    Explanation:

    System.nonoTime() is a monotonic time that increases only, it has no idea of what time it is right now, but it would only increase regardless. So it is a good way for measuring elapsing time. But you can not convert this into a sensible time as it has no reference to the current time.

    The provided method is a way to convert your stored nano time into a sensible time. First, you have a timeMs that is in nano time that you would like to convert. Then, you created another nanotime (i.e refMonoMs) and another System.currentTimeMillis() (i.e refUnixMx). Then you minus refMonoMs from the timeMs, and add the reference back into it to get the sensible time back.

提交回复
热议问题