获取某个时间的前一天
作者:互联网
import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Test { public static void main(String[] args) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date currentdate=new Date(); String systime= format.format(currentdate); System.out.println("当前系统时间:====="+systime); String curtime=getBeforeOneDay(currentdate); System.out.println("当前系统时间的前一天的时间:====="+curtime); System.out.println("得到某个时间的前一天的时间:====="+getBeforeOneDayByStringDate("20210407")); } /** * 获取当前系统时间的前一天时间 * @param dateStr * @return Date * @return */ public static String getBeforeOneDay(Date currentdate) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = Calendar.getInstance(); calendar.setTime(currentdate); calendar.add(Calendar.DAY_OF_MONTH, -1); currentdate = calendar.getTime(); String dayTime=format.format(currentdate); return dayTime; } public static String getBeforeOneDayByStringDate(String dateString) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d; try { d = format .parse(dateString); Calendar calendar = Calendar.getInstance(); calendar.setTime(d); calendar.add(Calendar.DAY_OF_MONTH, -1); // 在当前日基础上-1 System.out.println(format .format(calendar.getTime())); //获取String类型的时间 } catch (ParseException e) { e.printStackTrace(); } return format .format(calendar.getTime()); } }
标签:String,format,SimpleDateFormat,获取,某个,calendar,currentdate,Calendar,前一天 来源: https://www.cnblogs.com/zhangliang88/p/14628878.html