Common uses of the Date and calendar for JAVA

Source: Internet
Author: User
Tags date now

One, the date and string of the reciprocal usage, here need to use SimpleDateFormat

Date date = new Date ();
Set format
SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");

String strdate = Sdf.format (date);
String converted to date type
Date now = Sdf.parse (strdate);

Ii. the reciprocal transfer between date and calendar

Calendar cal = Calendar.getinstance ();
Cal.settime (New Date ());
Date date = Cal.gettime ();

Third, use the calendar to get the year, month, week, day, hour and other time domain

Cal.get (calendar.year);
Cal.get (Calendar.month);
Cal.get (Calendar.week);

Iv. Adding and reducing time

Cal.add (Calendar.month, 1);
Cal.add (calendar.week,2);
Cal.add (CALENDAR.MINUTE,-10);

One parameter of the Add method is the time domain (year, month, week, etc.) that needs to be added and minus, the parameter two-bit variance, the negative number represents the time forward (past), the so-called minus, encounters the cross-domain situation, for example, now is 2012-11, then executes Cal.add (calendar.month,3), Time will automatically change to 2013-02, then roll () method will not, the roll method will push the time to 2012-02, it only for the specified time domain, is not automatically cross-domain

Common uses of the Date and calendar for JAVA

Related Article

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.