推荐Calendar操作日期
Posted jinnian18sui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了推荐Calendar操作日期相关的知识,希望对你有一定的参考价值。
package com.example.demo.Calender;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CalenderController {
public static void main(String[] args){
System.out.println(getPastDate(1));
System.out.println(getPastMonth(2));
}
// 当前日期之前几天
private static String getPastDate(int past) {
Calendar calender = Calendar.getInstance();
calender.set(Calendar.DATE, calender.get(Calendar.DATE) - past);
Date today = calender.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String result = simpleDateFormat.format(today);
return result;
}
// 当前日期之前几月(同理年,秒,分钟)
private static String getPastMonth(int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - month);
Date today = calendar.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String result = simpleDateFormat.format(today);
return result;
}
}
package com.example.demo.Calender;
import org.junit.Before;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CalendarDemo {
Calendar calendar = null;
@Before
public void test(){
calendar = Calendar.getInstance();
}
/**
* Calendar 的月份从0开始 = 实际月份 - 1
*/
@Test
public void test1() {
System.out.println(calendar.get(Calendar.MONTH));
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 2);
System.out.println(calendar.get(Calendar.MONTH));
Date today = calendar.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String result = simpleDateFormat.format(today);
System.out.println(result);
}
}
以上是关于推荐Calendar操作日期的主要内容,如果未能解决你的问题,请参考以下文章