Detailed explanation of Java date conversion and example code
Java date conversion
Core classes involved: Date class, simpledateformat class and calendar class
1、 Date type and long type
Convert date type to long type
Date date = new Date();// Gets the current time date type
long date2long = date. getTime();// Date to long
Convert long type to date type
long cur = System. currentTimeMills();// Get the current time long return
Date long2date = new Date(cur);// Long to date
2、 Date type and string type
Convert date type to string type
Convert string type to date type
String str="2001-11-03 11:12:33.828";// Set initial string type date
Date str2date=sdf. parse(str);// String to date
3、 Date type and calendar type
Convert date type to calendar type
Calendar cal = Calendar. getInstance();// Gets the current time calendar type
cal. setTime(date); // Date to calendar
Convert calendar type to date type
Calendar cal = Calendar. getInstance();// Gets the current time calendar type
Date cal2date = cal. getTime();// Calendar to date
4、 Summary
5、 Interview questions
Q: Write a method. The parameter is date. Push the date back for 3 days and return the string type in the format of "yyyy MM DD"
Thank you for reading, hope to help you, thank you for your support to this site!