Conversion between date and calendar

Source: Internet
Author: User
Tags dateformat

1. Conversion between date and calendar:

 

Java code

  1. Date = new date ();
  2. Calendar calendar = calendar. getinstance ();
  3. Calendar. settime (date );
  4. Calendar. Add (calendar. Date,-1); // obtain the previous day
  5. Calendar. Add (calendar. Month,-1); // obtain the previous month.

In this way, the calendar instance can be used to obtain the date and time.

 

2. Conversion between date and string:

 

Java code

  1. String datestr = "2008-8-13 ";
  2. String Pattern = "yyyy-mm-dd ";
  3. Dateformate dateformat = new simpledateformat (pattern );
  4. Date = dateformat. parse (datestr );
  5. Date = dateformat. Format (date );

In this way, the instance date of a date can be converted to the calendar ar type, and then the date operation is performed.

3. Convert calendar to date

Calendar CA = calendar. getinstance ();

Date Ss = (date) Ca. gettime ();

4. the query date range cannot exceed one month

Import java. util. date;

Import java. util. calendar;

Import java. Text. simpledateformat;

Import java. Text. dateformat;

String start = '2017-01-02'

String end = '2017-02-12'

Dateformat = new simpledateformat ("yyyy-mm-dd ");

Try {

Date startdate = dateformat. parse (start );

Date enddate = datefformat. parse (end );

Calendar Cal = calendar. getinstance ();

Cal. settime (startdate );

Cal. Add (calendar. Month, + 1 );

Startdate = (date) Cal. gettime ();

If (startdate. gettime () <enddate. gettime ()){

Return "the query date range cannot exceed one month ";

} Catch (parseexception e ){

E. printstacktrace ();

}

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.