推荐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);
}

}
posted @ 2018-12-14 17:41  手中天  阅读(540)  评论(0编辑  收藏  举报