Javaã§æååã¨ãã¦åå¾ããæ¥ä»ããæ¥ä»åã«å¤æããããã«SimpleDateFormatã使ç¨ããæ¹æ³ãããã¾ããããã®SimpleDateFormatã®æ±ãã«ã¯æ³¨æãå¿ è¦ã§ãã
ä¾ãã°ã以ä¸ã®ããã«æ¬æ¥åå¨ããªãæ¥ä»ï¼2024/02/31ï¼ã§ãã©ã¼ãããããã¨è¯ããã¬ãã¨ãèµ·ãã¾ãã
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); System.out.println(sdf.parse("2024/02/31"));
å®è¡çµæã¯ä»¥ä¸ã®éãã§ãã
Sat Mar 02 00:00:00 JST 2024
ã¨ã©ã¼ã«ã¯ãªããã«ãåæã«ï¼2024/03/02ï¼ã«è§£éããã¾ãã
ä¸è¨ã®ãããªæåãããã§è¯ãã¨ããã±ã¼ã¹ã¯ãããããªãã¨æãã¾ãã
ãã®ãããªæåãé²ãã«ã¯ããã©ã¼ãããå¤æã®ã¡ã½ããå¼ã³åºãã®åã«ãDateFormatã®setLenientã¡ã½ããã«falseã渡ãã¦å¼ã³åºãã¦ããã¾ããããã¦ããã©ã¼ãããå¤æã¡ã½ãããå®è¡ããã¨ãç°å¸¸ãªå¤æã¨ãªãå ´åã¯ä¾å¤ãã¹ãã¼ãã¦ããã¾ãã
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); sdf.setLenient(false); System.out.println(sdf.parse("2024/02/31"));
å®è¡çµæã¯ä»¥ä¸ã®éãã§ãã
Exception in thread "main" java.text.ParseException: Unparseable date: "2024/02/31" at java.base/java.text.DateFormat.parse(DateFormat.java:403) at Sample.main(Sample.java:9)
JavaDocã®ãªã³ã¯ãå¼µã£ã¦ããã¾ãã
DateFormat (Java SE 23 & JDK 23)
ä¸è¨ã®éããç°å¸¸ãªå ´åã¯ä¾å¤ãã¹ãã¼ãã¦ãããã®ã§æå³ããªãå¤ã§å¾ç¶å¦çãå®è¡ãããã®ãé²ãã§ãããã¨ããæãã§ãã
å®ã¯æè¿ã¾ã§ä¸è¨ã®æ©è½ãç¥ããªãã¦ãæ£å¸¸ãªææ«æ¥ãåå¾ããªããã°ãããªãå ´åã«ããã¦ã以ä¸ã®ããã«java.util.Calendarã¯ã©ã¹ã使ç¨ãã¦ã¾ããã
int year = 2024; int month = 2; Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month - 1); cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); System.out.println(cal.getTime());
ç°å¸¸ãªå¤ã§å¾ç¶å¦çãå®è¡ããããã¨ãé²ãã¨åæã«ããããèªåçã«è£æ£ãããããªããã°ã©ã ãä½æãã¦ãã¾ãããã±ã¼ã¹ãã¤ã±ã¼ã¹ã ã¨ã¯æãã¾ãããæ¬æ¥ãªãã°ç°å¸¸ãªå¤ã渡ããããä¾å¤ãã¹ãã¼ããã®ãè¯ãããã§ãããã
çµè«ã¨ãã¦ã¯ãSimpleDateFormatã§æååããæ¥ä»åå¤æããå ´åã¯ãsetLenientãå¼ã³åºãã®ããã¹ãã«ãªã£ã¦ãããã§ããã
ä»åã¯ãã®è¾ºã§ãæå¾ã¾ã§ãèªã¿ããã ããããã¨ããããã¾ããã