根據(jù)當(dāng)前時(shí)間計(jì)算
獲取前后幾天
/**
* @Author: ljh
* @Description:獲取任意天后的時(shí)間
* @DateTime: 18:52 2022/11/23
* @Params: day 1表示后一天 -1表示前一天
* @Return
*/
public static String getDay(int day){
Calendar calendar2 = Calendar.getInstance();
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
calendar2.add(Calendar.DAY_OF_MONTH, day);
String date = sdf2.format(calendar2.getTime());
return date;
}
獲取前后幾個(gè)月
/**
* @Author: ljh
* @Description:獲取任意月后的時(shí)間
* @DateTime: 18:52 2022/11/23
* @Params: mon 1表示后一個(gè)月 -1表示前一個(gè)月
* @Return
*/
public static String getMon(int mon){
Calendar calendar2 = Calendar.getInstance();
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
calendar2.add(Calendar.MONTH, mon);
String date = sdf2.format(calendar2.getTime());
return date;
}
獲取前后幾年
/**
* @Author: ljh
* @Description: 獲取任意年后的時(shí)間
* @DateTime: 18:52 2022/11/23
* @Params: year 1表示后一年 -1表示前一年
* @Return
*/
public static String getYear(int year){
Calendar calendar2 = Calendar.getInstance();
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
calendar2.add(Calendar.YEAR, year);
String date = sdf2.format(calendar2.getTime());
return date;
}
根據(jù)指定時(shí)間計(jì)算
獲取前后幾天
/**
* @Author: ljh
* @Description:獲取任意天后的時(shí)間
* @DateTime: 18:52 2022/11/23
* @Params: time 指定的時(shí)間 day 1表示后一天 -1表示前一天
* @Return
*/
public static String getDay(String time, int day) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(time));
calendar.add(Calendar.DAY_OF_MONTH, day);
String date = sdf.format(calendar.getTime());
return date;
}
獲取前后幾個(gè)月
/**
* @Author: ljh
* @Description:根據(jù)指定時(shí)間獲取任意月后的時(shí)間
* @DateTime: 18:52 2022/11/23
* @Params: time 指定的時(shí)間 mon 1表示后一個(gè)月 -1表示前一個(gè)月
* @Return
*/
public static String getMon(String time, int mon) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(time));
calendar.add(Calendar.MONTH, mon);
String date = sdf.format(calendar.getTime());
return date;
}
獲取年后幾年
/**
* @Author: ljh
* @Description: 根據(jù)指定時(shí)間獲取任意年后的時(shí)間
* @DateTime: 18:52 2022/11/23
* @Params: time 指定的時(shí)間 year 1表示后一年 -1表示前一年
* @Return
*/
public static String getYear(String time, int year) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(time));
calendar.add(Calendar.YEAR, year);
String date = sdf.format(calendar.getTime());
return date;
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-558043.html
文章來源:http://www.zghlxwxcb.cn/news/detail-558043.html
到了這里,關(guān)于java根據(jù)當(dāng)前時(shí)間或指定時(shí)間獲取前后幾天或前后幾個(gè)月或前后幾年的時(shí)間的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!