Java date conversion, java date
Core classes involved:DateClass, SimpleDateFormatClass, CalendarClass
I. Date and long
- Convert Date type to long type
Date date = new Date (); // obtain the current time Date type
Long date2long = date. getTime (); // convert Date to long
- Convert long type to Date type
Long cur = System. currentTimeMills (); // gets the result of the long type at the current time.
Date long2date = new Date (cur); // convert long to Date
Ii. Date and String types
- Convert Date type to 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); // convert Date to String
- Convert String type to Date type
String str = "11:12:33. 828"; // you can specify the date of the initial string type.
Date str2date = sdf. parse (str); // convert String to Date
Iii. Date and Calendar
- Convert Date type to Calendar type
Calendar cal = Calendar. getInstance (); // gets the current time type of the Calendar.
Cal. setTime (date); // convert Date to Calendar
- Convert the Calendar type to the Date type
Calendar cal = Calendar. getInstance (); // gets the current time type of the Calendar.
Date cal2date = cal. getTime (); // convert Calendar to Date
Iv. Summary
- The conversion between the String and the basic type depends on the String. valueOf () method.
- The conversion between the Date and String classes depends on the SimpleDateFormat class.
- The conversion between Date and long relies on the construction provided by Date and the getTime () method.
- The Date and Calendar conversion depend on the setTime () and getTime () methods provided by Calendar.
5. Interview Questions
Q: Write A method. The parameter is Date date, which is pushed three days later. The string type is returned in the format of "yyyy-mm-dd ".
Public String add3Day (Date date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd ");
Calendar cal = Calendar. getInstance ();
Cal. setTime (date); // convert Date to Calendar ar
Cal. add (Calendar. DATE, 3); // push the DATE three days later. If it is reduced by three days, then-3. If the monthly value is increased, Calendar. MONTH
String after = sdf. format (cal. getTime (); // convert Calendar to Date and then to String
Return after;
}