每次用都要翻翻API,加强记忆
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
public class TestCalendar {
@Test
public void testCalendar() {
Calendar calendar = Calendar.getInstance();
System.out.println(calendarToString(calendar));
}
public String calendarToString(Calendar calendar) {
String str = calendar.get(Calendar.YEAR)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+calendar.get(Calendar.DATE);
return str;
}
/**
* 特定格式转换为Date对象
* @throws Exception
*/
@Test
public void testDate() throws Exception {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
Date date = df.parse("2015-6-6 19:21:30:456");
System.out.println(date);
}
/**
* 将Date转换为特定格式的字符串
*/
@Test
public void testDateToString() {
Date date = new Date();
System.out.println(dateToString(date));
}
public String dateToString(Date date) {
//2015-06-06 19:33:20:376
// return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(date);
//2015-6-6
return DateFormat.getDateInstance(DateFormat.DEFAULT).format(date);
//2015年6月6日 星期六
// return DateFormat.getDateInstance(DateFormat.FULL).format(date);
//2015-6-6
// return DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);
//15-6-6
// return DateFormat.getDateInstance(DateFormat.SHORT).format(date);
}
@Test
public void getSpecialDay() {
Calendar calendar = Calendar.getInstance();
//month从0开始,5即为6月
calendar.set(2015, 5, 6);
System.out.println(calendarToString(calendar));
//获取到前10天的日期
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE)-10);
System.out.println(calendarToString(calendar));
//获取到后10天的日期
calendar.set(2015, 5, 6);
calendar.set(Calendar.DATE,calendar.get(Calendar.DATE)+10);
System.out.println(calendarToString(calendar));
}
}