做项目的时候经常和时间打交道,每次都是重新写一遍,发现这样很吃亏,其实我一直都有写工具类的习惯,唯独没有对时间写一个专门的工具类,今天于是补上。暂时具有的功能比较少,以后如果遇到会在这里补上,另外如果大家有什么关于时间处理的需求也可以和我说一下,我会尽量去实现。
public class TimeHelper {
public static String getDate() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:MM:ss");
return format.format(getTime());
}
public static String getYear() {
return getDate().split(" ")[0].split("_")[0];
}
public static String getMounth() {
return getDate().split(" ")[0].split("_")[1];
}
public static String getDay(){
return getDate().split(" ")[0].split("_")[2];
}
public static String getHour(){
return getDate().split(" ")[1].split(":")[0];
}
public static String getMinute(){
return getDate().split(" ")[1].split(":")[1];
}
public static String getSecond(){
return getDate().split(" ")[1].split(":")[2];
}
public static Date getTime(){
return new Date();
}
/**
* 获取两个时间之间的天数
* 返回-1代表异常
* @return
*/
@SuppressWarnings("deprecation")
public static int getBetWeenDays(Date newtime, Date oldtime) {
if((newtime.getTime()-oldtime.getTime())<0)return -1;
int result = 0;
while (oldtime.compareTo(newtime) <= 0) {
result++;
oldtime.setDate(oldtime.getDate() + 1);
}
return result;
}
/**
* 获取两个时间之间的工作日数量
* @return
*/
@SuppressWarnings("deprecation")
public int getBetWeenWeekDays(Date newtime,Date oldtime){
if((newtime.getTime()-oldtime.getTime())<0)return -1;
int result = 0;
while (oldtime.compareTo(newtime) <= 0) {
if (oldtime.getDay() != 6 && oldtime.getDay() != 0)
result++;
oldtime.setDate(oldtime.getDate() + 1);
}
return result;
}
/**
* 获取两个时间之间的非工作日数量
* @return
*/
@SuppressWarnings("deprecation")
public int getBetWeenUnWeekDays(Date newtime,Date oldtime){
if((newtime.getTime()-oldtime.getTime())<0)return -1;
int result = 0;
while (oldtime.compareTo(newtime) <= 0) {
if (oldtime.getDay() ==0 && oldtime.getDay() == 6)
result++;
oldtime.setDate(oldtime.getDate() + 1);
}
return result;
}
public static void main(String[] args) {
int t=getBetWeenDays(new Date(), new Date(113, 7, 1));
System.out.println(t);
}
}