自定义时间工具类

package com.jredu.ch10;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {

/**
* 返回两个日期之间的相差天数

* @param d1
* @param d2
* @param patten
* @return
*/
public static int diffDay(String d1, String d2, String patten) {
int day = 0;
SimpleDateFormat format = new SimpleDateFormat(patten);
Date date1 = null;
Date date2 = null;
try {
date1 = format.parse(d1);
date2 = format.parse(d2);
long m = Math.abs(date1.getTime() - date2.getTime());
day = (int) (m / 1000 / 60 / 60 / 24);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return day;
}

/**
* 毫秒转日期

* @param m
* @return
*/
public static Date getDate(long m) {
return new Date(m);
}

/**
* 返回今天的日期
*/
public static Date getCurrentDate() {
return new Date();
}

/**
* 返回当前日期加减后的日期

* @param isPlus
* @param day
* @return
*/
public static Date getChangeDate(boolean isPlus, int day) {
// System.currentTimeMillis()获取当前时间的时间戳(自1970/01/01 00:00:00开始到当前经历的毫秒数)
long currentTime = System.currentTimeMillis();
long changeTime = 0;
if (isPlus) {
// 添加日期
changeTime = currentTime + (day * 24 * 60 * 60 * 1000);
} else {
// 减少日期
changeTime = currentTime - (day * 24 * 60 * 60 * 1000);
}
return new Date(changeTime);
}

/**
* 返回指定日期的加减天数

* @param isPlus
* @param day
* @param date
* @return
*/
public static Date getChangeDate(boolean isPlus, int day, Date date) {
long time = date.getTime();
long changeTime = 0;
if (isPlus) {
// 添加日期
changeTime = time + (day * 24 * 60 * 60 * 1000);
} else {
// 减少日期
changeTime = time - (day * 24 * 60 * 60 * 1000);
}
return new Date(changeTime);
}

/**
* 日期格式化

* @param date
* @param format
* @return
*/
public static String getFormatDate(Date date, String format) {
// 创建格式化日期对象
SimpleDateFormat sdf = new SimpleDateFormat(format);
// 将日期格式化后返回格式化字符串
return sdf.format(date);
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值