您的位置:首页 > 其它

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

2017-02-22 10:56 302 查看
//日期的加减操作

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("明天大于今天");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: