日期工具类

`/**

  • 日期工具类。

*/
public class DateUtils {

/**
 * 提供一个日期,然后通过指定的模式格式化,然后返回日期的字符串。 Date --------> String 的转换。
 * 
 * @param date    要格式化的日期
 * @param pattern 按照什么来格式化日期(2021-07-23 11:14:19)。
 * @return
 */
public static String formatDate(Date date, String pattern) {
	DateFormat df = new SimpleDateFormat(pattern);
	return df.format(date);
}

/**
 * 提供日期字符串,然后通过特定的模式,返回Date。 String -------> Date 的转换。
 * 
 * @param date    日期字符串。
 * @param pattern 按照什么来解析日期(2021-07-23 11:14:19)。
 * @return
 */
public Date parseDate(String date, String pattern) {
	return null;
}

/**
 * 输入身份证号码,然后得到这个人活了多少天。
 * 
 * @param idCard
 * @return
 */
public static long computeDateToNowWithDay(String idCard) throws Exception {

	// 从身份证号码里面截取“生日”
	String birthday = idCard.substring(6, 14);
	// 解析的格式
	String pattern = "yyyyMMdd";
	// 把字符串的日期转成java.util.Date
	DateFormat df = new SimpleDateFormat(pattern);
	// 解析得到日期
	Date birth = df.parse(birthday);
	// 算这个人出生的日期的毫秒数
	long l1 = birth.getTime();
	// 获取当前的日期
	Date now = new Date();
	// 拿到当前日期的毫秒数
	long l2 = now.getTime();
	// 计算毫秒数的差
	long minus = l2 - l1;
	// 把毫秒数转成天数。
	long days = minus / 1000 / 60 / 60 / 24;
	return days;
}

}`

posted @ 2022-01-07 13:56  shark_zzz  阅读(11)  评论(0)    收藏  举报