Date, string, and calendar convert each other

Source: Internet
Author: User
Tags try catch

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.