简体   繁体   中英

Want to get the start and end date of a month from a particular date

I m having a code which gives date of a particular event like:

String date=date1.substring(3,5)+"/"+date1.substring(0,2)+"/"+date1.substring(6,10);

I want the start date and end date of the month of which the above date belongs to..

Kindly help.

Use Calendar.getActualMaximum()

To get the max date of the month

cal.getActualMaximum(Calendar.DAY_OF_MONTH)

and for minimum

cal.getActualMinimum(Calendar.DAY_OF_MONTH)

Note: cal is an instance of Calendar

I would personally recommend using Joda Time for pretty much all date and time work in Java.

First I'd parse the original value into a LocalDate , then:

// Parse using DateTimeFormatter.parseDateTime().toLocalDate();
LocalDate original = ...; 
LocalDate startOfMonth = original.dayOfMonth().withMinimumValue();
LocalDate endOfMonth = original.dayOfMonth().withMaximumValue();

(For the start of the month, you could just use original.withDayOfMonth(1) of course.)

you should consider using java.util.Calendar . You provide a java.util.Date , then you can get all fields. A field would be YEAR , DAY

EDIT (for comment)

I'll assume that in your code snippet date1 is a string... it also seems that you know the format (mm/dd/yyyy or dd/mm/yyyy), so first you need a SimpleDateFormat :

final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); // or dd/MM/yyyy

Then you'll need a way to parse the date... parsing a date means to convert from a string to a date object:

final Date date = dateFormat.parse(date1); // date1 is a date in a string in the given format

You have a Date now... All you need is to extract information from it using a java.util.Calendar

final Calendar calendar = new Calendar();
calendar.setTime(date);

With the calendar , you can get any date-related information. The first day of the month is trivial... any month starts with day number one... But for the last day of the month you need to get the maximum value for the DAY_OF_MONTH field:

int lastDayOfTheMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

Anyway, I'm not making any of this stuff up... Feel free to browse the Calendar javadoc and the SimpleDateFormat javadoc . It's all there, and I'm sure it is better explained than by me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM