Date, time and date class. Here we talk about the util package, not the sql package
Date: indicates a specific time instant, accurate to milliseconds (1000 milliseconds = 1 second)
Time and date operations are based on milliseconds
Time origin: January 1, 1970, 0:00:00, 0:00, 0:00
Get the millisecond value of the current time:
public class DateDemo { public static void main(String[] args) { long l = System.currentTimeMillis(); //Get the milliseconds value of the current date System.out.println(l); //1515639742854 } }
Construction method of Date class:
package demo; import java.util.Date; public class DateDemo { public static void main(String[] args) { function1(); function2(); } public static void function1(){ Date date = new Date(); System.out.println(date); //Output: Thu Jan 11 11:09:41 CST 2018 } public static void function2(){ Date date = new Date(123456); System.out.println(date); //Output: Thu Jan 01 08:02:03 CST 1970 } }
Method of Date class:
package demo; import java.util.Date; public class DateDemo { public static void main(String[] args) { function1(); function2(); } public static void function1(){ //Date to MS Date date = new Date(); long time = date.getTime(); System.out.println(time); //1515642454307 } public static void function2(){ //Millisecond to date Date date = new Date(); System.out.println(date); //Thu Jan 11 11:47:34 CST 2018 date.setTime(123123); System.out.println(date); //Thu Jan 01 08:02:03 CST 1970 } }
We find that the Date format obtained by the Date class is not what we are used to,
So here is a DateFormat class that provides the function of formatting dates:
DateFormat is an abstract class, which mainly uses its subclass SimpleDateFormat class
Example:
package demo; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; //Format date public class SimpleDateFormatDemo { public static void main(String[] args) { function(); } public static void function(){ DateFormat date = new SimpleDateFormat("yyyy year MM month dd day HH spot mm Minute ss second"); String date1 = date.format(new Date()); System.out.println(date1); //Output: 12:01:30 on January 11, 2018 } }
You can also convert strings to dates:
Example:
package demo; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; //Format date public class SimpleDateFormatDemo { public static void main(String[] args) throws ParseException { function(); } public static void function() throws ParseException { // There are exceptions here, which will be introduced later DateFormat date1 = new SimpleDateFormat("yyyy-MM-dd"); // Must be a string in standard format Date date2 = date1.parse("2017-11-25"); System.out.println(date2); // Output: Sat Nov 25 00:00:00 CST 2017 } }
In actual development, users will not be allowed to enter dates by themselves, because there is a risk of formatting errors
Usually make a date control for the user to choose, rather than let the user input