Date is a class used to process time in jdk1.0. However, due to the restrictions on date internationalization, calendar is released in jdk1.1. Many date methods are outdated, all are migrated to the calendar.
1. Convert date to string
Date date = new Date();SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");String dateString = dateFormat.format(date);
Note: simpledateformat is a subclass of dateformat and can be used to format date.
2. Convert string to date
String dateString = "2014-09-26";SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");Date date = dateFormat.parse(dateString);
Note: The parse method throws an checked exception and requires the programmer to make a declaration or try catch.
3. Convert calendar to string
Calendar calendar = Calendar.getInstance();SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");String dateString = dateFormat.format(calendar.getTime());
Note: The gettime method of the calendar returns the date type.
4. Convert string to calendar
String dateString = "2014-09-26";SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");Date date = dateFormat.parse(dateString);Calendar calendar = Calendar.getInstance();calendar.setTime(date);System.out.println(calendar);
5. Convert calendar to date
Calendar calendar = Calendar.getInstance();Date date = calendar.getTime();
6. Convert date to calendar
Calendar calendar = Calendar.getInstance();calendar.setTime(new Date());
Date, string, and calendar convert each other