java_14 Date

时间:2022-04-12 11:48:34

1.Date类的构造方法

  Date是表示时间的类
  空参构造
    public Date()

    public class Demo {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
}
  }

java_14 Date

  带参构造
    public Date(long times)

    public static void main(String[] args) {
Date date = new Date(30000);
System.out.println(date);
}

java_14 Date
2.Date类的get和set方法
    public long getTime()
    将当前的日期对象,转为对应的毫秒值

    public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
long time = date.getTime();
System.out.println(time);
}

java_14 Date
    public void setTime(long times);
   根据给定的毫秒值,生成对应的日期对象

    public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
date.setTime(30000);
System.out.println(date);
}

java_14 Date
3.日期格式化SimpleDateFormat

    public static void main(String[] args) {
SimpleDateFormat s1 = new SimpleDateFormat();
String sd = s1.format(new Date());
System.out.println(sd);
}

java_14 Date

    public static void main(String[] args) {
SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd");
String sd = s1.format(new Date());
System.out.println(sd);
}

java_14 Date

4.DateFormat类

  parse  将字符串  解析为  日期的对象,即从1970年到输入的年与日的毫秒数

    public static void main(String[] args) throws ParseException {
SimpleDateFormat s1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = s1.parse("1993-6-23");
long time = date.getTime();
System.out.println(time);
}

java_14 Date
5 Calendar类

  Calendar 类是一个抽象类,所以不能直接new一个对象出来

  get()方法:获得当前日历的年月日

    public static void main(String[] args) {
Calendar c = Calendar.getInstance(); //不能直接new
int year = c.get(Calendar.YEAR); //用Calendar.YEAR方法获得年
int month = c.get(Calendar.MONTH)+1; //月份是从0开始计算的
int day = c.get(Calendar.DAY_OF_MONTH); //获得日
System.out.println(year);
System.out.println(month);
System.out.println(day);
}

java_14 Date

  set(int field,int value)方法:设置日历

    public static void main(String[] args) {
Calendar c = Calendar.getInstance();
c.set(2022, 4, 23);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);    //注意此处不加1
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println(year);
System.out.println(month);
System.out.println(day);
}

java_14 Date

  add    日历偏移量

    public static void main(String[] args) {
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, 30); //往后增加30天
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH)+1;
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println(year);
System.out.println(month);
System.out.println(day);
}

java_14 Date