本文主要是介绍实现日期往前或往后或跳转到指定月份或天数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
//月份跳转
//初始日期
String yearMonth = "201702";
String yearMonthStr = "";//往前(负数)或往后(正数)
int add = -2;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");Date source = sdf.parse(yearMonth);
Calendar cal = Calendar.getInstance();
cal.setTime(source);
cal.add(Calendar.MONTH, add);
yearMonthStr = sdf.format(cal.getTime());
System.out.println(yearMonthStr);
-------------------------------------------------------------------------------------
//天跳转
String yearMonth = "20170208";
String yearMonthStr = "";
int add = 3;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date source = sdf.parse(yearMonth);
Calendar cal = Calendar.getInstance();
cal.setTime(source);
cal.add(Calendar.DATE, add);
yearMonthStr = sdf.format(cal.getTime());
System.out.println(yearMonthStr);
这篇关于实现日期往前或往后或跳转到指定月份或天数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!