Get the number of days, weeks, and months, since Epoch in Java

前端 未结 7 788
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 18:05

I\'m trying to get the number of days, weeks, months since Epoch in Java.

The Java Calendar class offers things like calendar.get(GregorianCalendar.DAY_OF_YEAR), or

7条回答
  •  盖世英雄少女心
    2020-12-01 18:27

    I wouldn't expect there to be an elegant way of doing it since it is not a very common requirement. I can't help but wonder why you want to do it...

    But anyway, the way I would do it is to subtract the epoch date from the Calendar and then get the fields you want:

    Calendar timeSinceEpoch = Calendar.getInstance();
    timeSinceEpoch.add(Calendar.YEAR, -1970);
    
    int yearsSinceEpoch = timeSinceEpoch.get(Calendar.YEAR);
    int monthsSinceEpoch = timeSinceEpoch.get(Calendar.MONTH) + 12 * yearsSinceEpoch;
    

提交回复
热议问题