TimeUtils
public class TimeUtils {
public static final int YEAR = 0;
public static final int MONTH = 1;
public static final int DAY = 2;
public static final int HOUR = 3;
public static final int MINUTE = 4;
private static final DecimalFormat sDecimalFormat = new DecimalFormat("00");
@SuppressLint("SimpleDateFormat")
private static final SimpleDateFormat sDate24HourFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@SuppressLint("SimpleDateFormat")
private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
private TimeUtils() {
/* cannot be instantiated */(http://www.amjmh.com/v/)
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* 获取当前年份
*/
public static int getYear() {
return getYear("");
}
public static int getYear(String year) {
if (TextUtils.isEmpty(year)) {
return new Date().getYear() + 1900;
}
return Integer.valueOf(year);
}
/**
* 获取当前月份
*/
public static int getMonth() {
return getMonth("");
}
public static int getMonth(String month) {
if (TextUtils.isEmpty(month)) {
return new Date().getMonth() + 1;
}
return Integer.valueOf(month);
}
/**
* 获取当前日期
*/
public static int getDay() {
return getDay("");
}
public static int getDay(String day) {
if (TextUtils.isEmpty(day)) {
return new Date().getDate();
}
return Integer.valueOf(day);
}
/**
* 获取当前小时
*/
public static int getHour() {
return getHour("");
}
public static int getHour(String hour) {
if (TextUtils.isEmpty(hour)) {
return new Date().getHours();
}
return Integer.valueOf(hour);
}
/**
* 获取当前分钟
*/
public static int getMinute() {
return getMinute("");
}
public static int getMinute(String minute) {
if (TextUtils.isEmpty(minute)) {
return new Date().getMinutes();
}
return Integer.valueOf(minute);
}
/**
* 根据年月日获取星期几
*/
public static int getDayOfWeek(int year, int month, int day) {
Calendar instance = Calendar.getInstance();
instance.set(Calendar.YEAR, year);
instance.set(Calendar.MONTH, month - 1);
instance.set(Calendar.DAY_OF_MONTH, day);
return instance.get(Calendar.DAY_OF_WEEK);
}
/**
* 传递星期几获取当月相同星期的具体日期
*
* @param targetDayOfWeek 星期,targetDayOfWeek=Calendar.SUNDAY~SATURDAY
* @return [15, 20]
*/
public static List<Integer> getDayOfMonthsByDayOfWeek(int year, int month, int targetDayOfWeek) {
int maxDayOfMonth = getDayOfMonthByYearAndMonth(year, month);
List<Integer> dayOfWeeks = new ArrayList<>();
for (int i = 1; i <= maxDayOfMonth; i++) {
int dayOfWeek = getDayOfWeek(year, month, i);
if (dayOfWeek == targetDayOfWeek) {
dayOfWeeks.add(i);
}
}
return dayOfWeeks;
}
public static int getWeekByStr(Context context, String week) {
if (TextUtils.equals(week, context.getString(R.string.sunday))) {
return Calendar.SUNDAY;
} else if (TextUtils.equals(week, context.getString(R.string.monday))) {
return Calendar.MONDAY;
} else if (TextUtils.equals(week, context.getString(R.string.tuesday))) {
return Calendar.TUESDAY;
} else if (TextUtils.equals(week, context.getString(R.string.wednesday))) {
return Calendar.WEDNESDAY;
} else if (TextUtils.equals(week, context.getString(R.string.thursday))) {
return Calendar.THURSDAY;
} else if (TextUtils.equals(week, context.getString(R.string.friday))) {
return Calendar.FRIDAY;
} else if (TextUtils.equals(week, context.getString(R.string.saturday))) {
return Calendar.SATURDAY;
} else {
return -1;
}
}
/**
* 获取某年某月的最大天数
*/
public static int getDayOfMonthByYearAndMonth(int year, int month) {
Calendar instance = Calendar.getInstance();
instance.set(Calendar.YEAR, year);
instance.set(Calendar.MONTH, month - 1);
return instance.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* 计算两个日期之间的总秒数
*/
public static int getTotalSeconds(LocalTime startTime, LocalTime endTime) {
if (endTime.hour < startTime.hour) endTime.day += 1; // 计算时间不需要理会超过当前月份天数问题,超过一天直接+1计算
DateModel dateModel = new DateModel(startTime, endTime);
return dateModel.getBetweenSeconds();
}
/**
* 根据提供的开始年月日时分和秒数,计算经过seconds秒后的具体日期
*
* @return [year, month, day, hour] 通过TimeUtils上的常量索引YEAR、MONTH、DAY、HOUR、MINUTE获取
*/
public static int[] getEndDate(int year, int month, int day, int hour, int minute, int seconds) {
long startTime = new Date(year, month, day, hour, minute).getTime();
long endTime = startTime + seconds * 1000;
int[] endDateArr = new int[5];
Date endDate = new Date(endTime);
endDateArr[YEAR] = endDate.getYear();
endDateArr[MONTH] = endDate.getMonth();
endDateArr[DAY] = endDate.getDate();
endDateArr[HOUR] = endDate.getHours();
endDateArr[MINUTE] = endDate.getMinutes();
int dayOfMonth = getDayOfMonthByYearAndMonth(endDateArr[YEAR], endDateArr[MONTH]);
// 计算的天数超过了当月的总天数,月份+1
if (endDateArr[DAY] > dayOfMonth) {
endDateArr[MONTH]++;
endDateArr[DAY] = 1;
// 计算的月份超过了总月份,年份+1
if (endDateArr[MONTH] > 12) {
endDateArr[YEAR]++;
endDateArr[MONTH] = 1;
}
}
return endDateArr;
}
public static boolean isMonthValid(int month) {
return month >= 0 && month <= 12;
}
public static boolean isHourValid(int hour) {
return hour >= 0 && hour <= 23;
}
public static boolean isMinuteValid(int minute) {
return minute >= 0 && minute <= 59;
}
/**
* 根据秒数获取格式化时分秒
*
* @return 00:00:00
*/
public static String getDecimalFormatTime(int seconds) {
String hour = sDecimalFormat.format(seconds / 3600);
String minute = sDecimalFormat.format(seconds % 3600 / 60);
String second = sDecimalFormat.format(seconds % 60);
return hour + ":" + minute + ":" + second;
}
/**
* 根据年月日时分秒获取当前时区的时间(已处理夏令时)
*
* @return 00:00:00
*/
public String formatZoneTime(Context context, int year, int month, int day, int hour, int minute, int second) {
String zone = TimeZone.getDefault().getID();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return formatZoneTimeAndroidO(context, createLocalDateTime(year, month, day, hour, minute, second), ZoneId.of(zone));
} else {
TimeZone timeZone = TimeZone.getTimeZone(zone);
Calendar.getInstance().setTimeZone(timeZone);
SimpleDateFormat format = NtpTimeUtils.is24HourFormat(context) ? sDate24HourFormat : sDateFormat;
format.setTimeZone(timeZone);
return timeFormat(format, getDateTime(year, month - 1, day, hour, minute, second));
}
}
public String timeFormat(SimpleDateFormat format, long time) {
return timeFormat(format, new Date(time));
}
public String timeFormat(SimpleDateFormat format, Date date) {
return format.format(date);
}
/**
* 传递年月日时分秒获取日期Date
*/
public Date getDateTime(int year, int month, int day, int hour, int minute, int second) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month); // 需要注意Calendar的月份计算时要-1,获取时要+1
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
return calendar.getTime(); // Date.getTime()获取时间戳
}
@RequiresApi(Build.VERSION_CODES.O)
private LocalDateTime createLocalDateTime(int year, int month, int day, int hour, int minute, int second) {
return LocalDateTime.of(year, month, day, hour, minute, second);
}
@RequiresApi(Build.VERSION_CODES.O)
private String formatZoneTimeAndroidO(Context context, LocalDateTime time, ZoneId zoneId) {
ZonedDateTime zonedDateTime = time.atZone(ZoneId.systemDefault());
ZonedDateTime zoneSameInstant = zonedDateTime.withZoneSameInstant(zoneId);
long hours = Duration.between(zoneSameInstant.withEarlierOffsetAtOverlap(),
zoneSameInstant.withLaterOffsetAtOverlap()).toHours();
zoneSameInstant = zoneSameInstant.plusHours(hours);
String format = NtpTimeUtils.is24HourFormat(context) ? "yyyy-MM-dd HH:mm:ss" : "yyyy-MM-dd hh:mm:ss";
return zoneSameInstant.format(DateTimeFormatter.ofPattern(format));
}
/**
* 0时区的Mjd转换为当前时区日期
*
* @param zeroMjd 0时区Mjd
* @return 当前时区日期
*/
public LocalTime mjdToLocal(MjdTime zeroMjd) {
LocalTime zeroTime = mjdToDate(zeroMjd.mjdDate);
if (zeroTime != null) {
zeroTime.hour = zeroMjd.mjdTime / 3600;
zeroTime.minute = (zeroMjd.mjdTime % 3600) / 60;
zeroTime.second = ((zeroMjd.mjdTime % 3600) % 60);
return adjustZoneTime(zeroTime);
}
return null;
}
/**
* Mjd转为0时区日期
*/
public LocalTime mjdToDate(int mjd) {
if (mjd != 0) {
int year = (int) ((((float) mjd) - 15078.2) / 365.25);
int month = (int) ((((float) mjd) - 14956.1 - (int) (((float) year) * 365.25)) / 30.6001);
int day = (int) (mjd - 14956 - ((int) (((float) month) * 365.25)) - ((int) (((float) month) * 30.6001)));
int k = ((month == 14 || month == 15) ? 1 : 0);
year = (int) (year + k + 1900);
month = month - 1 - k * 12;
// int weekday = ((mjd + 2) % 7) + 1;
LocalTime zeroTime = new LocalTime();
zeroTime.year = year;
zeroTime.month = month;
zeroTime.day = day;
}
return null;
}
/**
* 日期转为Mjd
*/
public int dateToMjd(int year, int month, int day) {
if (year < 1900) return -1;
int il = (1 == month) || (2 == month) ? 1 : 0;
year = year - 1900;
return 14956 + day + (int) (((float) (year - il)) * 365.25) + (int) (((float) (month + 1 + il * 12)) * 30.6001);
}
/**
* 0时区Mjd转换为当前时区Mjd
*
* @param zeroMjd 0时区Mjd
* @return 当前时区的Mjd
*/
public MjdTime zeroMjdToLocalMjd(MjdTime zeroMjd) {
LocalTime localTime = mjdToLocal(zeroMjd);
int localMjdDate = dateToMjd(localTime.year, localTime.month, localTime.day);
int localMjdTime = getCurrTimeZoneMjdTotalSeconds();
MjdTime localMjd = new MjdTime();
localMjd.mjdDate = localMjdDate;
localMjd.mjdTime = localMjdTime;
return localMjd;
}
/**
* 获取当前时区从00:00:00到现在的总秒数(已处理夏令时)
*/
private int getCurrTimeZoneMjdTotalSeconds() {
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
return second + minute * 60 + hour * 3600;
}
/**
* 0时区日期转换为当前时区日期
*
* @param zeroTime 0时区日期
* @return 当前时区日期
*/
public LocalTime adjustZoneTime(LocalTime zeroTime) {
return adjustZoneTime(zeroTime, TimeZone.getTimeZone("GMT"), TimeZone.getDefault());
}
/**
* 旧时区日期转换为新时区日期
*
* @param oldTime 旧时区日期
* @param oldTimeZone 旧时区,默认为底层的0时区
* @param newTimeZone 新时区,默认为当前时区
* @return 新时区日期
*/
public LocalTime adjustZoneTime(LocalTime oldTime, TimeZone oldTimeZone, TimeZone newTimeZone) {
return adjustZoneTime(oldTime.year, oldTime.month, oldTime.day, oldTime.hour, oldTime.minute, oldTime.second, oldTimeZone, newTimeZone);
}
public LocalTime adjustZoneTime(int year, int month, int day, int hour, int minute, int second, TimeZone oldTimeZone, TimeZone newTimeZone) {
Date oldDate = getDateTime(year, month - 1, day, hour, minute, second);
int timeOffset = oldTimeZone.getOffset(oldDate.getTime()) - newTimeZone.getOffset(oldDate.getTime()); // 时区之间的时间差
Date newDate = new Date(oldDate.getTime() - timeOffset);
Calendar calendar = Calendar.getInstance();
calendar.setTime(newDate);
LocalTime localTime = new LocalTime();
localTime.year = calendar.get(Calendar.YEAR);
localTime.month = calendar.get(Calendar.MONTH) + 1;
localTime.day = calendar.get(Calendar.DAY_OF_MONTH);
localTime.hour = calendar.get(Calendar.HOUR_OF_DAY);
localTime.minute = calendar.get(Calendar.MINUTE);
localTime.second = calendar.get(Calendar.SECOND);
return localTime;
}
}
public class LocalTime {
public int year;
public int month;
public int day;
public int hour;
public int minute;
public int second;
}
// TimeUtils中的儒略历时间MjdTime默认都是0时区,所以也处理了时区日期转换操作,根据需要取舍是否转换时区
public class MjdTime {
public int mjdDate;
public int mjdTime;
}
public class DateModel {
private final LocalTime start;
private final LocalTime end;
public DateModel(LocalTime start, LocalTime end) {
this.start = start;
this.end = end;
}
public int getBetweenSeconds() {
long seconds = getDate(end).getTime() - getDate(start).getTime();
if (seconds < 0) {
return 0;
}
return (int) (seconds / 1000);
}
private Date getDate(LocalTime localTime) {
return new Date(localTime.year, localTime.month, localTime.day, localTime.hour, localTime.minute);
}
public LocalTime getStart() {
return start;
}
public LocalTime getEnd() {
return end;
}
}
---------------------