java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

java得出两个日期之间所有日期

近日老要跑系统日志,每次发生问题要遍历每日的情况。代码改了好几次,每次输入的日期变化,都要修改不少代码。于是写了个日期类来调用。
包含以下功能
1.判断是否为闰年
2.判断一个月有几天
3.得出两个日期直接所有日期

package com.javaer.common;

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

/**
 * java时间类
 * 
 * @author mc2
 * 
 */
public class JTime {
	static String dateFormat = "yyyy-MM-dd";
	static SimpleDateFormat format = new SimpleDateFormat(dateFormat);

	/**
	 * 获取两个日期之间所有的日期
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static ArrayList days(String date1, String date2) {
		ArrayList L = new ArrayList();
		if (date1.equals(date2)) {
			System.out.println("两个日期相等!");
			return L;
		}

		String tmp;
		if (date1.compareTo(date2) > 0) { // 确保 date1的日期不晚于date2
			tmp = date1;
			date1 = date2;
			date2 = tmp;
		}

		tmp = format.format(str2Date(date1).getTime() + 3600 * 24 * 1000);

		int num = 0;
		while (tmp.compareTo(date2) < 0) {
			L.add(tmp);
			num++;
			tmp = format.format(str2Date(tmp).getTime() + 3600 * 24 * 1000);
		}

		if (num == 0)
			System.out.println("两个日期相邻!");
		return L;
	}

	private static Date str2Date(String str) {
		if (str == null)
			return null;

		try {
			return format.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 判断是否闰年
	 * 
	 * @param year
	 * @return
	 */
	public static boolean isLeapYear(int year) {
		return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0));
	}

	/**
	 * 一个月有几天
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public static int dayInMonth(int year, int month) {
		boolean yearleap = isLeapYear(year);
		int day;
		if (yearleap && month == 2) {
			day = 29;
		} else if (!yearleap && month == 2) {
			day = 28;
		} else if (month == 4 || month == 6 || month == 9 || month == 11) {
			day = 30;
		} else {
			day = 31;
		}
		return day;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		JTime jt = new JTime();
		System.out.println(jt.days("2012-02-02", "2012-03-23"));
	}

}

结果

[2012-02-03, 2012-02-04, 2012-02-05, 2012-02-06, 2012-02-07, 2012-02-08, 2012-02-09, 2012-02-10, 2012-02-11, 2012-02-12, 2012-02-13, 2012-02-14, 2012-02-15, 2012-02-16, 2012-02-17, 2012-02-18, 2012-02-19, 2012-02-20, 2012-02-21, 2012-02-22, 2012-02-23, 2012-02-24, 2012-02-25, 2012-02-26, 2012-02-27, 2012-02-28, 2012-02-29, 2012-03-01, 2012-03-02, 2012-03-03, 2012-03-04, 2012-03-05, 2012-03-06, 2012-03-07, 2012-03-08, 2012-03-09, 2012-03-10, 2012-03-11, 2012-03-12, 2012-03-13, 2012-03-14, 2012-03-15, 2012-03-16, 2012-03-17, 2012-03-18, 2012-03-19, 2012-03-20, 2012-03-21, 2012-03-22]


This entry was posted in JAVA and tagged , , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-time-days/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply