时间工具类

本文介绍了一个用于处理日期和时间的工具类,包括获取当前日期、时间的各部分、计算两个日期间的天数等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

做项目的时候经常和时间打交道,每次都是重新写一遍,发现这样很吃亏,其实我一直都有写工具类的习惯,唯独没有对时间写一个专门的工具类,今天于是补上。暂时具有的功能比较少,以后如果遇到会在这里补上,另外如果大家有什么关于时间处理的需求也可以和我说一下,我会尽量去实现。

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失落夏天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值