Java Caledar class determines the number of weeks this week
Ideas
- First create SimpleDateFormat to format the time
- Create Calendar class. Because it is an abstract class, you cannot use the new method, but use getInstance.
- Foreigners believe that the first day of the week is Sunday, while Chinese people believe that the first day of the week is Monday. So first call the setFirstDayOfWeek method to set Monday to the first day of the week
- First get the local time to calculate the current number of weeks: Use WEEK_OF_YEAR in the Calendar class
- Get the target date to calculate the number of weeks
- The number of weeks obtained is of type int, so compare values
Solve the problem
- Print this week’s bill, judge the duration of the activity, etc.
- After getting the current number of weeks, you can traverse the stored date array. Those days are the current week.
accomplish
public static void main(String[] args) throws Exception{ //Format time SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); // Create a new calendar class Calendar c=(); //Set Monday as the first day (); // Create a new formatted today's String class date String todayStr=(new Date()); //Convert to Date type Date today=(todayStr); //Set calendar time (today); //Get the current number of weeks int currentWeekNum=(Calendar.WEEK_OF_YEAR); (currentWeekNum); //Date to be queried String str="2022-3-28"; Date date=(str); (date); //The number of weeks of query date int selWeekNum=(Calendar.WEEK_OF_YEAR); (selWeekNum); if(currentWeekNum==selWeekNum){ (str+"It's the date of the current week"); }else{ (str+"Not the date of the current week"); } }
Calendar on how to use Zhou
Create an object
Calendar calendar = ();
Get how many weeks are in the specified year
Calendar calendar = ();
Passed in parameters, year, for example: 2023
(, 2023);
Get weeks
int week = ();
If you need to specify the start time of a week, you can use the function
(Calendar.DAY_OF_WEEK, );
Get the specified week, the specified year, the return month and the date
```java >//Create an object>Calendar calendar = (); >// Set year>(,2023); >// Set, for example, get the date of Monday (Calendar.DAY_OF_WEEK, ); // What week of the year (Calendar.WEEK_OF_YEAR,36); // Get month. Requires +1. Because the month starts at 0 int i = (())+1; (i); // Get the date of that week, Monday ((Calendar.DAY_OF_MONTH));
Follow-up questions: About If January 1 is not Monday, then define this week as the last week of the previous year.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.