Java Date Conversion
Core classes involved: Date class, SimpleDateFormat class, Calendar class
Date type and long type
The date type is converted to a long type
Date date = new Date ();//Get Current time Date type
Long Date2long = Date.gettime ();//date long
Long converts to date type
Long cur = system.currenttimemills ();//Get current time long return
Date long2date = new date (cur);//long to date
Date type and String type
The date type is converted to a string type
Date date = new Date ();
SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss". SSS ");//Set the target conversion format to YYYY-MM-DD HH:mm:ss. SSS
String date2string = Sdf.format (date);//date to String
string conversion 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
Date Type and calendar type
The date type is converted to a calendar type
Calendar cal = Calendar.getinstance ();//Get current time calendar type
Cal.settime (date); Date Change Calendar
The calendar type converts to the date type
Calendar cal = Calendar.getinstance ();//Get current time calendar type
Date cal2date = Cal.gettime ();//calendar to date
Iv. Summary
- The conversion between string and base type depends on the string.valueof () method
- The conversion between date and string classes depends on the SimpleDateFormat class
- Date and long conversions rely on date-provided constructs and the gettime () method
- Date and calendar conversions depend on the settime () and gettime () methods provided by the calendar.
Five, interview questions
Q: Write a method, the parameter is date date, push date back 3 days, return the string type in "YYYY-MM-DD" format
Public String add3day (date date) throws parseexception{
SimpleDateFormat sdf = new SimpleDateFormat ("Yyyy-mm-dd"); C2/>calendar cal = Calendar.getinstance ();
Cal.settime (date);//date convert to Calendar
cal.add (calendar.date, 3);//Push the date back 3 days, reduce 3 days-3. Monthly increase is calendar.month
after = Sdf.format (Cal.gettime ()),//calendar converted to date, and then converted to string return after
;
}
Thank you for reading, I hope to help you, thank you for your support for this site!