您的位置:首页 > 编程语言 > Java开发

Java对日期的处理

2015-09-10 16:04 260 查看
目标日期与现在日期的间隔天数以及日期间的比较

/**
* 获取指定日期 格式如:yyyy-mm-dd
*
* @param day
*            距离当前日期的天数
* @return
*/
public static String getSpecifyDate(int day) {
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, -(day));
String beforeDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar
.getTime());
return beforeDate;
}
/**
* 获取指定日期 格式如:yyyy-mm-01
* 根据int 返回 int 前几天
* @param day
*            距离当前日期的天数
* @return
*/
public static String getYesterday(int day) {
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, -(day));
String beforeDate = new SimpleDateFormat("yyyy-MM-01").format(calendar
.getTime());
return beforeDate;
}

/**
* 时间比较
*
* @param nowTime
*            当前系统时间
* @param compareTime
*            用于比较的时间
* @return
* @author zhangzhongjian
*/
public static int compareDate(String nowTime, String compareTime) {
DateFormat dformate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
int tmp = 0;
try {
Date sysTime = dformate.parse(nowTime);
Date planTime = dformate.parse(compareTime);
if (sysTime.getTime() > planTime.getTime()) {
tmp = 1; // 当前时间大于比较时间
} else if (sysTime.getTime() < planTime.getTime()) {
tmp = -1; // 当前时间小于于比较时间
} else {
tmp = 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return tmp;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: