Java date conversion details and example code

  • 2020-05-16 06:57:48
  • OfStack

Java date conversion

Core classes involved: Date class, SimpleDateFormat class, Calendar class

1.Date and long

Conversion from the Date type to the long type

Date date = new Date(); // gets the current time of type Date

long date2long = date. getTime (); / / Date long

Conversion from the long type to the Date type

long cur = System. currentTimeMills (); // returns the current time of type long

Date long2date = new Date(cur); / / long Date

2. Date and String

Conversion from type Date to type String


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 turn String

Conversion from type String to type Date

String str = "2001-11-03 11:12:33. 828"; // sets the initial string type date

Date str2date = sdf. parse (str); / / String Date

3. Date and Calendar

Conversion from type Date to type Calendar

Calendar cal = Calendar. getInstance (); // gets the current time of type Calendar

cal. setTime (date); / / Date Calendar

Conversion from Calendar type to Date type

Calendar cal = Calendar. getInstance (); // gets the current time of type Calendar

Date cal2date = cal. getTime (); / / Calendar Date

4. To summarize

The conversion between String and the base type depends on the String.valueOf () method The conversion between the Date and String classes depends on the SimpleDateFormat class The Date to long conversion relies on the constructs provided by Date and the getTime() method The conversion from Date to Calendar relies on the setTime() and getTime() methods provided by Calendar

5. The interview questions

Q: write 1 method with the parameter Date date, push date back 3 days, and return the string type in the "yyyy-mm-dd" format


public String add3Day(Date date) throws ParseException{
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  Calendar cal = Calendar.getInstance();
  cal.setTime(date);//Date convert Calendar
  cal.add(Calendar.DATE, 3);// Push back the date 3 Day, reduce the 3 Day, -3.  To increase the Calendar.MONTH
  String after = sdf.format(cal.getTime());//Calendar convert Date And then convert to String
  return after;
}

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: