Date class
Constructor
- Date()
- Date(long millisec)//The number of milliseconds since January 1, 1970
Get the current date and time.toString()
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
// 初始化 Date 对象
Date date = new Date();
// 使用 toString() 函数显示日期时间
System.out.println(date.toString());
}
}
Date comparison
- The getTime() method obtains two dates (the number of milliseconds since January 1, 1970), and then compares the two values.
- before(),after() 和 equals()。
- For example, if the 12th of a month is earlier than the 18th, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
- compareTo()
format
- SimpleDateFormat
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
HH is a 24-hour clock, and hh is a 12-hour clock.
- printf
System.out.printf("全部日期和时间信息:%tc",date);
System.out.printf("HH:MM格式(24时制):%tR",date);
//b的使用,月份简称
String str=String.format(Locale.US,"英文月份简称:%tb",date);
System.out.printf("本地月份简称:%tb%n",date);
//B的使用,月份全称
str=String.format(Locale.US,"英文月份全称:%tB",date);
System.out.printf("本地月份全称:%tB%n",date);
//a的使用,星期简称
str=String.format(Locale.US,"英文星期的简称:%ta",date);
//A的使用,星期全称
System.out.printf("本地星期的简称:%tA%n",date);
//C的使用,年前两位
System.out.printf("年的前两位数字(不足两位前面补0):%tC%n",date);
//y的使用,年后两位
System.out.printf("年的后两位数字(不足两位前面补0):%ty%n",date);
//j的使用,一年的天数
System.out.printf("一年中的天数(即年的第几天):%tj%n",date);
//m的使用,月份
System.out.printf("两位数字的月份(不足两位前面补0):%tm%n",date);
//d的使用,日(二位,不够补零)
System.out.printf("两位数字的日(不足两位前面补0):%td%n",date);
//e的使用,日(一位不补零)
System.out.printf("月份的日(前面不补0):%te",date);
Calendar class
The Calendar class is an abstract class that implements a specific subclass object in actual use. The process of creating an object is transparent to the programmer, and only needs to be created using the getInstance method.
Calendar c = Calendar.getInstance();//默认是当前日期
//创建一个代表2009年6月12日的Calendar对象
c.set(2009, 6 - 1, 12);//public final void set(int year,int month,int date)
Setting of Calendar class object information
- set()
c.set(Calendar.DATE,10);
c.set(Calendar.YEAR,2008);
- add()
c.add(Calendar.DATE, 10);//c也就表示为10天后的日期
c.add(Calendar.DATE, -10);//c也就表示为10天前的日期