Java基础知识之日期操作

来源:互联网 发布:淘宝京润珍珠是真的吗 编辑:程序博客网 时间:2024/06/04 00:41

1.获取当前年、月、日期

//日历类Calendar calendar = Calendar.getInstance();//获取年份int year = calendar.get(Calendar.YEAR);//获取月份 需要  +1int month = calendar.get(Calendar.MONTH) + 1;//获取天数日期int day = calendar.get(Calendar.DATE);//获取当前时间为本周的第几天(国外以星期天为第一天)int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);//获取当前时间为本月的第几天int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);//获取当前时间为本年的第几天int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);

2.使显示时间 xxxx年xx月xx日形式

//HH为24小时格式,hh为12小时格式;//yyyy代表年份,如“2017”,MM代表月份,如“03”,dd代表天,如“24”//EEEE代表星期,如“星期五”;MMMM代表中文月份,如“三月”;SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 EEEE HH:mm:ss");//设置日期格式System.out.println(df.format(new Date()));
3.获取现在时间距离指定时间的间隔日期
//日期字符串转换为日期SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//指定日期String objectTime = "2022-02-22 22:22:22";try {java.util.Date date = simpleDateFormat.parse(objectTime);//将指定日期转换为毫秒long second1 = date.getTime();//得到当前时间的毫秒值long second2 = System.currentTimeMillis();//计算时间差long difference = second2 - second1;//换算成天数int day = (int) (difference/1000/60/60/24);System.out.println(day);} catch (ParseException e) {e.printStackTrace();}
4.判断两个时间段是否有重合的部分
public static boolean isOverlap(String startdate1, String enddate1, String startdate2, String enddate2) {//日期字符串转换为日期SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");Date leftStartDate = null;Date leftEndDate = null;Date rightStartDate = null;Date rightEndDate = null;try {leftStartDate = simpleDateFormat.parse(startdate1);leftEndDate = simpleDateFormat.parse(enddate1);rightStartDate = simpleDateFormat.parse(startdate2);rightEndDate = simpleDateFormat.parse(enddate2);} catch (ParseException e) {return false;}//通过将日期转换为毫秒值进行比较 然后值 true有重合,false 无重合return ((leftStartDate.getTime() >= rightStartDate.getTime())&& leftStartDate.getTime() < rightEndDate.getTime())|| ((leftStartDate.getTime() > rightStartDate.getTime())&& leftStartDate.getTime() <= rightEndDate.getTime())|| ((rightStartDate.getTime() >= leftStartDate.getTime())&& rightStartDate.getTime() < leftEndDate.getTime())|| ((rightStartDate.getTime() > leftStartDate.getTime())&& rightStartDate.getTime() <= leftEndDate.getTime());}
boolean isOverLap1 = isOverlap("2001-12-11 12:22:22", "2002-12-11 12:22:22", "2002-10-11 11:21:21", "2002-12-12 12:22:22");boolean isOverLap2 = isOverlap("2001-12-11 12:22:22", "2002-12-11 12:22:22", "2003-10-11 11:21:21", "2004-12-12 12:22:22");

isOverLap1 为true 时间段有重合

isOverLap2 为false 时间无重合





0 0
原创粉丝点击