Get the current date and the week of the year

java code   favorite code
  1. String today = "2013-01-14";  
  2. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
  3. Date date = null;  
  4. try {  
  5.     date = format.parse(today);  
  6. catch (ParseException e) {  
  7.     // TODO Auto-generated catch block  
  8.     e.printStackTrace();  
  9. }  
  10.   
  11. Calendar calendar = Calendar.getInstance();  
  12. calendar.setFirstDayOfWeek(Calendar.MONDAY);  
  13. calendar.setTime(date);  
  14.   
  15. System.out.println(calendar.get(Calendar.WEEK_OF_YEAR));  

 

A somewhat complicated code is used to judge the number of weeks that the date belongs to in the current year. When looking at the Calendar class, I saw WEEK_OF_YEAR, which is very practical. But there is a small problem with the time, for example, 2010-01-03, the returned result is 2 (that is, the second week of 2010), because the United States uses Sunday as the first day of the week.

  I thought of changing the starting day of the week, setFirstDayOfWeek(int value), passed a 1, and wanted to set Monday as the first day, but it didn't work. After checking the document, it will be fine to change it to Calendar.MONDAY, but I don’t know why it is not easy to use 1, but just use Calendar.MONDAY?

  

  Supplement: I checked the "constant field value" again, and found that the value of MONDAY is not 1 at all, but 2.

  SUNDAY :1

  WORLD :2

  TUESDAY :3

  WEDNESDAY :4

  THURSDAY : 5

  FRIDAY : 6

  SATURDAY :7

Guess you like

Origin blog.csdn.net/zs520ct/article/details/79828278