Java gets the first day of the month and the last day to get the first and last day of the previous one months

Source: Internet
Author: User

SimpleDateFormat format = new SimpleDateFormat ("Yyyy-mm-dd");

Get the first day of the previous month
Calendar cal_1=calendar.getinstance ();//Get current date
Cal_1.add (Calendar.month,-1);
Cal_1.set (calendar.day_of_month,1);//set to number 1th, the current date is the first day of the month
FirstDay = Format.format (Cal_1.gettime ());
SYSTEM.OUT.PRINTLN ("-----1------firstday:" +firstday);
Get the last day of the previous month
Calendar cale = Calendar.getinstance ();
Cale.set (calendar.day_of_month,0);//set to number 1th, the current date is the first day of the month
Lastday = Format.format (Cale.gettime ());
SYSTEM.OUT.PRINTLN ("-----2------Lastday:" +lastday);


Get the first day of the current month:
Calendar C = calendar.getinstance ();
C.add (calendar.month, 0);
C.set (calendar.day_of_month,1);//set to number 1th, the current date is the first day of the month
String first = Format.format (C.gettime ());
System.out.println ("===============first:" +first);

Get the last day of the current month
Calendar CA = Calendar.getinstance ();
Ca.set (Calendar.day_of_month, Ca.getactualmaximum (Calendar.day_of_month));
String last = Format.format (Ca.gettime ());
System.out.println ("===============last:" +last);

Get the first and last day of a month in a year

Calendar cal = Calendar.getinstance ();
Do not add the following 2 lines, the first and last day of the one months before the current time
Cal.set (calendar.year,2012);
Cal.set (Calendar.month, 6);
Cal.set (Calendar.day_of_month, 1);
Cal.add (Calendar.day_of_month,-1);
String lastdate = Format.format (Cal.gettime ());

Cal.set (Calendar.day_of_month, 1);
String firstdate = Format.format (Cal.gettime ());

System.out.println (lastdate+ "<--->" +firstdate);

Java gets the first day of the month and the last day to get the first and last day of the previous one months

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.