Java获取昨天,任意一天的日期

取昨天的日期,本想的截出来日期减一就好了。又一想不对,如果今天是一号怎么办?

    现有两个办法

1:Date as = new Date(new Date().getTime()-24*60*60*1000);
  SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
  String time = matter1.format(as);
  System.out.println(time);

  取出数字型的时间  再减去24*60*60*1000,就得到昨天的时间了;

这个有点过时了!

2:Calendar   cal   =   Calendar.getInstance();
  cal.add(Calendar.DATE,   -1);
  String yesterday = new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime());
  System.out.println(yesterday);

这个方法很方便,年月日都可以随心所欲的变!


猜你喜欢

转载自blog.csdn.net/tiankongcheng6/article/details/79755366