An overview of Java's Date class and SimpleDateFormal class

Date class

1.1 Overview of Date

The java.util.Date` class represents a specific instant, accurate to milliseconds.

Continue to check the description of the Date class and find that Date has multiple constructors, but some of them are outdated. Let's focus on the following two constructors

  • public Date(): The value of milliseconds from the moment when the program is running to the origin of time is converted into a Date object, and the Date object is allocated and initialized to represent the time when it is allocated (accurate to milliseconds).

  • public Date(long date): Convert the millisecond value date of the specified parameter into a Date object, allocate the Date object and initialize this object to represent the standard reference time (called "epoch"), that is, 00:00 on January 1, 1970: 00 GMT) for the specified number of milliseconds.

Tips: Since China is located in the East Eighth District (GMT+08:00), it is a time zone 8 hours ahead of the Universal Coordinated Time/Greenwich Mean Time (GMT). When GMT is 0:00, the standard time in the East Eighth District is 08 :00.

To put it simply: use the no-argument structure to automatically set the millisecond time of the current system time; specify the long type construction parameter to customize the millisecond time. For example:

import java.util.Date;
public class Demo01Date {
    public static void main(String[] args) {
        // 创建日期对象,把当前的时间
        System.out.println(new Date()); // Tue Jan 16 14:37:35 CST 2020
        // 创建日期对象,把当前的毫秒值转成日期对象
        System.out.println(new Date(0L)); // Thu Jan 01 08:00:00 CST 1970
    }
}

tips: When using the println method, the toString method in the Date class is automatically called. The Date class overrides the toString method in the Object class, so the result is a string in the specified format.

1.2 Common methods of Date

Most of the methods in the Date class are outdated, and the commonly used methods are:

  • public long getTime()Convert the date object to the corresponding time millisecond value.

  • public void setTime(long time)Sets the millisecond value given by the method parameter to the date object

sample code

public class DateDemo02 {
    public static void main(String[] args) {
        //创建日期对象
        Date d = new Date();
        
        //public long getTime():获取的是日期对象从1970年1月1日 00:00:00到现在的毫秒值
        //System.out.println(d.getTime());
        //System.out.println(d.getTime() * 1.0 / 1000 / 60 / 60 / 24 / 365 + "年");
        //public void setTime(long time):设置时间,给的是毫秒值
        //long time = 1000*60*60;
        long time = System.currentTimeMillis();
        d.setTime(time);
        System.out.println(d);
    }
}

Summary: Date represents a specific instant of time, and we can use the Date object to operate on time.

SimpleDateFormat class

java.text.SimpleDateFormatIt is a date/time formatting class. Through this class, we can help us complete the conversion between date and text, that is, we can convert back and forth between Date object and String object.

  • Formatting : Convert the Date object to a String object according to the specified format.

  • Parsing : Convert the String object to a Date object according to the specified format.

2.1 Construction method

Since DateFormat is an abstract class and cannot be used directly, common subclasses are required java.text.SimpleDateFormat. This class requires a schema (format) to specify formatting or parsing criteria. The construction method is:

  • public SimpleDateFormat(String pattern): Constructs a SimpleDateFormat with the given pattern and the default locale's date format symbols. The parameter pattern is a string representing a custom format for datetime.

2.2 Format Rules

Common formatting rules are:

Identification letter (case sensitive) meaning
y Year
M moon
d Day
H hour
m point
s Second

Note: For more detailed format rules, please refer to the API documentation of the SimpleDateFormat class.

2.3 Common methods

Common methods of the DateFormat class are:

  • public String format(Date date): Formats a Date object as a string.

  • public Date parse(String source): Parses a string into a Date object.

    package com.itheima.a01jdk7datedemo;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class A03_SimpleDateFormatDemo1 {
        public static void main(String[] args) throws ParseException {
            /*
                public simpleDateFormat() 默认格式
                public simpleDateFormat(String pattern) 指定格式
                public final string format(Date date) 格式化(日期对象 ->字符串)
                public Date parse(string source) 解析(字符串 ->日期对象)
            */
            //1.定义一个字符串表示时间
            String str = "2023-11-11 11:11:11";
            //2.利用空参构造创建simpleDateFormat对象
            // 细节:
            //创建对象的格式要跟字符串的格式完全一致
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = sdf.parse(str);
            //3.打印结果
            System.out.println(date.getTime());//1699672271000
        }
        private static void method1() {
            //1.利用空参构造创建simpleDateFormat对象,默认格式
            SimpleDateFormat sdf1 = new SimpleDateFormat();
            Date d1 = new Date(0L);
            String str1 = sdf1.format(d1);
            System.out.println(str1);//1970/1/1 上午8:00
            //2.利用带参构造创建simpleDateFormat对象,指定格式
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
            String str2 = sdf2.format(d1);
            System.out.println(str2);//1970年01月01日 08:00:00
            //课堂练习:yyyy年MM月dd日 时:分:秒 星期
        }
    }

Summary: DateFormat can convert Date objects and strings to each other.

2.4 Exercise 1 (date of birth of first love girlfriend)

/*
     假设,你初恋的出生年月日为:2000-11-11
     请用字符串表示这个数据,并将其转换为:2000年11月11日
     创建一个Date对象表示2000年11月11日
     创建一个SimpleDateFormat对象,并定义格式为年月日把时间变成:2000年11月11日
*/
//1.可以通过2000-11-11进行解析,解析成一个Date对象
String str = "2000-11-11";
//2.解析
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf1.parse(str);
//3.格式化
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
String result = sdf2.format(date);
System.out.println(result);

2.5 Exercise 2 (Second Kill Activity)

/* 需求:
            秒杀活动开始时间:2023年11月11日 0:0:0(毫秒值)
            秒杀活动结束时间:2023年11月11日 0:10:0(毫秒值)
            小贾下单并付款的时间为:2023年11月11日 0:01:0
            小皮下单并付款的时间为:2023年11月11日 0:11:0
            用代码说明这两位同学有没有参加上秒杀活动?
         */
//1.定义字符串表示三个时间
String startstr = "2023年11月11日 0:0:0";
String endstr = "2023年11月11日 0:10:0";
String orderstr = "2023年11月11日 0:01:00";
//2.解析上面的三个时间,得到Date对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
Date startDate = sdf.parse(startstr);
Date endDate = sdf.parse(endstr);
Date orderDate = sdf.parse(orderstr);
//3.得到三个时间的毫秒值
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long orderTime = orderDate.getTime();
//4.判断
if (orderTime >= startTime && orderTime <= endTime) {
    System.out.println("参加秒杀活动成功");
} else {
    System.out.println("参加秒杀活动失败");
}

Guess you like

Origin blog.csdn.net/qq_69748833/article/details/132656384