需求
用Java把字符串表示的日期按要求自动变为多少天前,多少天后?
代码
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Hello {
// @author 孙琨
public static void main(String[] args) {
// TODO Auto-generated method stub
// Date d = new Date();
// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// String dateNowStr = sdf.format(d);
// System.out.println("格式化后的日期:" + dateNowStr);
// boolean s1 = true;
// boolean s2 = true;
// boolean s = false;
// s = s1 && s2;
// System.out.println(s);
String logDay = "20170501";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
try {
Date date = sdf.parse(logDay);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(calendar.DATE, -1); // 负数为提前几天,正数为推迟几天
date = calendar.getTime();
String greenDay = sdf.format(date);
System.out.println(greenDay);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}