当前位置: 代码迷 >> 综合 >> 日期操作(日期加减,格式化,比较)
  详细解决方案

日期操作(日期加减,格式化,比较)

热度:92   发布时间:2023-10-19 02:24:34.0
//日期的加减操作
Calendar cal=Calendar.getInstance();//获得一个Calendar类型的通用对象
  //不用new,是因为Calendar是一个抽象类,它的构造方法是protected的, //所以无法使用Calendar类的构造方法来创建对象
cal.setTime(new Date());//将Date对象反应到一个Calendar对象中
cal.add(Calendar.DAY_OF_MONTH,1);//在指定日期上加指定天数(当前日期加1天)
      //Calendar的其它常量决定在哪个日期上进行加减,比如Calendar.HOUR,小时//上加减
Date tomorrow=cal.getTime();


//日期的格式化操作
SimpleDateFormat simpleDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr=simpleDate.format(new Date());//将指定日期转换成指定格式的字符串
Date date=simpleDate.parse(String dateStr);//将String字符串转换成指定格式的Date类型


//日期比较
Calendar calNow=Calendar.getInstance();
calNow.setTime(new Date());
if(cal.compareTo(calNow)>0){//Calendar 类型比较
System.out.println("明天大于今天");
}

Date now=new Date();
if(tomorrow.getTime()>now.getTime()){//Date类型比较
System.out.println("明天大于今天");
}
  相关解决方案