Common uses for date and calendar in Java

Source: Internet
Author: User

The most time class used in Java is java.util.Date,
Because the date class takes GetYear (), GetMonth () and other methods of obtaining the year, month, and day obsolete,
So use calendar to get the date format of the year, month, day, week and more commonly used


Note: The following code has been tested in jdk1.6, other versions may be used differently, please note!


Conversion between date and string

/** * Date and string of the reciprocal usage, here need to use SimpleDateFormat */date currenttime = new Date (); SimpleDateFormat formatter = new SimpleDateFormat ("Yyyy-mm-dd"); String datestring = Formatter.format (currenttime);D ate Date = Formatter.parse (datestring);


The interaction between date and calendar

/** * */calendar cal = calendar.getinstance () between Date and Calendar, Cal.settime (New Date ());D ate date1 = Cal.gettime ();


Use the calendar to get the year, month, week, day, hour, and other time domains

/** * Use Calendar to get year, month, week, day, hour and other time domain */cal.get (calendar.year); Cal.get (Calendar.month); Cal.get (Calendar.week_of_month) ; Cal.get (Calendar.day_of_month);


To add or subtract time

/** * Increase and decrease the time */cal.add (Calendar.month, 1); System.out.println (Cal.gettime ());


Calculate the day of the week for a given date

calendarcal = Calendar.getinstance (); Cal.set (2016,08,01);  string[] strdays = new string[] {"SUNDAY", "MONDAY", "Tuesday", "Wednesday", "Thursday", "FRIDAY", "SATURDAY"}; System.out.println (Strdays[cal.get (Calendar.day_of_week)-1]);

This article is from the "Craneyuan" blog, make sure to keep this source http://craneyuan.blog.51cto.com/9365548/1834462

Common uses for date and calendar in Java

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.