package com.smartlab.myapplication; import android.os.Build; import androidx.annotation.RequiresApi; import java.util.function.Function; public class TimeHelp { private int year; private int month; private int day; private int hour; private int minute; private int second; public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } public int getHour() { return hour; } public void setHour(int hour) { this.hour = hour; } public int getMinute() { return minute; } public void setMinute(int minute) { this.minute = minute; } public int getSecond() { return second; } public void setSecond(int second) { this.second = second; } @Override public String toString() { return String.format("%d年%d月%d日%d时%d分%d秒", year, month, day, hour, minute, second); } @RequiresApi(api = Build.VERSION_CODES.N) public static TimeHelp foo(int timestamp) { TimeHelp dt = new TimeHelp(); long minutes = timestamp / 60; dt.second = (int) (timestamp % 60); long hours =8+(minutes / 60); // 格林威治时间比北京时间晚8小时,必须加8 dt.minute = (int) (minutes % 60); long days = hours / 24; dt.hour = (int) (hours % 24); Function<Integer, Boolean> isLeapYear = y -> (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; int year = 1970; long restDays = days; while (true) { int daysOfYear = isLeapYear.apply(year) ? 366 : 365; if (restDays < daysOfYear) break; restDays -= daysOfYear; year++; } dt.year = year; int[] daysOfMonth = {31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; daysOfMonth[1] = isLeapYear.apply(dt.year) ? 29 : 28; for ( int i = 0; i < daysOfMonth.length; i++) { if (restDays < daysOfMonth[i]) { dt.month = i + 1; break; } restDays -= daysOfMonth[i]; } dt.day = (int) restDays; if (dt.hour > 0 || dt.minute > 0 || dt.second > 0) { //多出来的一天 dt.day += 1; } return dt; } }