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;
}
}
---------------------

TimeUtils的更多相关文章

  1. java的TimeUtils或者DateUtils的编写心得

    一.几种常见的日期和时间类介绍 介绍时间工具类不可避免必须要去触碰几个常见的日期和时间类,所以就简单介绍一下. 1.jdk1.8之前的日期时间类 a.Date类 我们可以通过new的方式生成一个Dat ...

  2. TimeUtils(没试过)

    package util; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseExc ...

  3. 放弃安卓原生TimePicker,选择wheelView打造更漂亮的时间get,以及动态拉伸输入框布局,这些,这里都有!

    最近公司要求的上线项目有这么一个需求,要写一个请假申请的页面,里面必须有请假开始时间,结束时间,还有一个请假原因. 于是想到时间选择嘛,官方不是有个DatePicker吗?额,是不是要DatePick ...

  4. java工具类

    1.HttpUtilsHttp网络工具类,主要包括httpGet.httpPost以及http参数相关方法,以httpGet为例:static HttpResponse httpGet(HttpReq ...

  5. 【开源】MQTT推送服务器——zer0MqttServer(Java编写)

    目录 说明 功能 如何使用 参考帮助 说明 重要的放前面:V1.0版本是一个非常基础的版本,除了完整的MQTT协议实现外,其他功能什么都没做. MQTT 协议是 IBM 开发的即时通讯协议,相对于 I ...

  6. ObjectAnimator.start()工作原理

    分析下面一段代码的逻辑 objectAnimator.start(); 他会调用父类的start(),即ValueAnimator,我们分析valueAnimator.start()即可 ValueA ...

  7. Android开发常用工具类

    来源于http://www.open-open.com/lib/view/open1416535785398.html 主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前 ...

  8. storm启动过程之源码分析

    TopologyMaster: 处理拓扑的一些基本信息和工作,比如更新心跳信息,拓扑指标信息更新等   NimbusServer: ** * * NimbusServer work flow: 1. ...

  9. 你应该知道的那些Android小经验

    原文出处:http://jayfeng.com/ 做Android久了,就会踩很多坑,被坑的多了就有经验了,闲暇之余整理了部分,现挑选一些重要或者偏门的“小”经验做个记录. 查看SQLite日志 ad ...

随机推荐

  1. [BZOJ 4455] [ZJOI 2016] 小星星 (树形dp+容斥原理+状态压缩)

    [BZOJ 4455] [ZJOI 2016] 小星星 (树形dp+容斥原理+状态压缩) 题面 给出一棵树和一个图,点数均为n,问有多少种方法把树的节点标号,使得对于树上的任意两个节点u,v,若树上u ...

  2. 使用autotools自动生成Makefile并在此之上使用dh-make生成可发布的deb程序包(详解)

    转自:http://blog.csdn.net/longerzone/article/details/12705507 一.前言 本文将介绍如何使用autotools生成一个Makefile文件,并在 ...

  3. 7.golang的字符串 string

    golang 字符串为不可变的量 ,字符串定义要使用双引号 package main import "fmt" func main() { var xx string = 'xxx ...

  4. CSUST 8.4 早训

    ## Problem A A - Memory and Crow CodeForces - 712A 题意: 分析可得bi=ai+ai+1 题解: 分析可得bi=ai+ai+1 C++版本一 #inc ...

  5. jmeter性能测试抛除工具用命令测试的方法

    1.我们有时会遇到那种图片或文件大的传输数据,容易将jmeter测试工具卡死,这个时候就需要抛除测试工具,直接用命令进行测试(window和linux都适用) 2.首先在jmeter工具上把性能测试脚 ...

  6. java中的四种引用方式(强引用,软引用,弱引用,虚引用)

    java内存管理主要有内存分配和内存回收,都不需要程序员负责,垃圾回收的机制主要是看对象是否有引用指向该对象. java中对象的引用主要有四种:强引用,软引用,弱引用,虚引用. Java中提供这四种引 ...

  7. 方法签名_spring aop_around

    //注解签名 方法签名 Signature signature = pjp.getSignature(); MethodSignature methodSignature= (MethodSignat ...

  8. JS 的 Browser对象

    Window对象 closed innerHeight    窗口文档显示区的高度,包括滚动条 outerHeight    窗口总高度,包括工具条和滚动条 open() close() alert( ...

  9. 【玩转Eclipse】——eclipse实现代码块折叠-类似于VS中的#region……#endregion

    [玩转Eclipse]——eclipse实现代码块折叠-类似于VS中的#region……#endregion http://www.cnblogs.com/Micheal-G/articles/507 ...

  10. 四、续绑定SignaIR的用户管理-(添加好友和消息盒子)

    一.聊天消息表(普通消息,申请消息,群聊消息) CREATE TABLE MSG_INFO ( MSG_Id INT PRIMARY KEY AUTO_INCREMENT, -- 消息标识 MSG_T ...