想根据指定字符串日期,获取是第几周,结果报错了

java.text.ParseException: Unparseable date: "2023-03-07"at java.text.DateFormat.parse(DateFormat.java:366)at com.hidata.hidbm.Test11.getWeeksInMonthOfDate(Test11.java:27)at com.hidata.hidbm.Test11.main(Test11.java:14)20233月第2Process finished with exit code 0

经过查找,发现是因为SimpleDateFormat里面忘记加 “yyyy-MM-dd”,
原来的

SimpleDateFormat df=new SimpleDateFormat();

改过后

 SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");

最终代码

package com.hidata.hidbm;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;/** * @Description : * @Date: 2023-03-07 10:05 */public class Demo{public static void main(String[] args) {System.out.println(getWeeks("2023-03-07"));}/** * 获取指定日期-XXXX年X月第X周 */public static String getWeeks(String dateStr){SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");Calendar calendar = Calendar.getInstance();try {calendar.setTime(df.parse(dateStr));} catch (ParseException e) {e.printStackTrace();}//设置每周第一天为周一 默认每周第一天为周日calendar.setFirstDayOfWeek(Calendar.MONDAY);//获取当前日期所在周周日calendar.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);return String.valueOf(calendar.get(Calendar.YEAR)).concat("年").concat(String.valueOf(calendar.get(Calendar.MONTH)+1)).concat("月第").concat(String.valueOf(calendar.get(Calendar.WEEK_OF_MONTH))).concat("周");}}