1. 获取当期日期、年份、月份
import
java.util.Calendar;
public class
Main {
public static void
main(String[] args) {
Calendar now = Calendar.getInstance();
System.out.println(
"Current Year is : "
+ now.get(Calendar.YEAR));
// month start from 0 to 11
System.out.println(
"Current Month is : "
+ (now.get(Calendar.MONTH) +
1
));
System.out.println(
"Current Date is : "
+ now.get(Calendar.DATE));
}
}
2. 获取前一天、前一个月的日期
Calendar calendar = Calendar.getInstance();//
此时打印它获取的是系统当前时间
calendar.add(Calendar.DATE, -1); //得到前一天
String yestedayDate
= new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
calendar.add(Calendar.MONTH, -1); //
得到前一个月
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH)+1; //输出前一月的时候要记得加
1
3. 字符串转为日期格式
String date = "2010-02-01 23:59:59";
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try
{
Date d = sf.parse(date);
System.out.println(sf.format(d));
} catch (ParseException e) {
e.printStackTrace();
}