ãã®è¨äºã¯ã¯ã¦ãªã¨ã³ã¸ã㢠Advent Calendar 2023 - Hatena Developer Blogã®1/1ã®è¨äºã§ãã
1904å¹´ã«ãªã£ã¦ãã¾ãã¾ãããä»å¹´ããããããé¡ããã¾ããid:nakatakiã§ãã
è¾°å¹´çã¾ããªã®ã§å¹´ç·â¦ã¨è¨ãããã¨ããã§ãããã©ããã年表示ãå£ãã¦ãã¾ã£ã¦ããããã§ãããã®åå ã¯dayjsã®ä»æ§ã®ç©´ã«ããã¾ãããä¸ç·ã«åå ãæ¢ãã¦ã¿ã¾ãããã
以ä¸ã®ãããªã³ã³ãã¼ãã³ããããã¾ããã(éè¦ãªé¨åã ããã¾ã¨ããä»®ã®ãã®ã§ã)
const DateInput: React.FC = () => { const [selectedDate, setSelectedDate] = useState(""); const onChange = (event: React.ChangeEvent<HTMLInputElement>) => { const inputDate = event.target.value; const parsedDate = dayjs(inputDate, "YYYY-MM-DD"); if (parsedDate.isValid()) { // æ¬æ¥ã¯è²ã å¦çãã setSelectedDate(parsedDate.format("YYYY-MM-DD")); } else { // invalidãªãä»æ¥ã®æ¥ä»ã«ãã¦ãã setSelectedDate(dayjs().format("YYYY-MM-DD")); } }; return ( <input type="date" max="9999-12-31" value={selectedDate} onChange={onChange} /> ); };
ããã¯ãdayjsã¨ããæ¥æå¦çã©ã¤ãã©ãªãå©ç¨ãããå¹´ææ¥ãå ¥åããã³ã³ãã¼ãã³ãã§ããä¼¼ãæ©è½ãæã¤Moment.jsãæ°è¦éçºãåæ¢ããã®ã§ãä¹ãæããâ¦ã¨ããæ¹ãå¤ãã¨æãã¾ãã ãã®ãããªè¡¨ç¤ºã«ãªãã¾ãã
ããã§ã¯ãæ§ã ãªäºæ ã«ãããdayjsã«ããããªãã¼ã·ã§ã³ãçµç±ãããã¼ã¿ãããä¸åº¦inputã«æ»ãã¦ãã¾ãã
ãã®ç¶æ ã§ä¸åº¦æ¥ä»ãé¸æãããã¼ãã¼ãã§è©¦ãã«ã1234ãã¨æã¡è¾¼ãã§ã¿ãã¨â¦
ãªãã ããï¼
ã1901å¹´â1902å¹´â1903å¹´â1904å¹´ãã¨ç»é¢ãé·ç§»ãã¦ãã¾ã£ã¦ãã¾ããä½ãå ¥åãã¦ããã®èª¿åã ã ããã2024ããå ¥åãã¦ãã1904ãã«ãªã£ã¦ãã¾ã£ããã§ããã
åå
dayjsã®ã³ã¼ãã¼ã±ã¼ã¹
ãããªã£ã¦ããåå ã¯ãç¾å¨ã®dayjsã®ã³ã¼ãã¼ã±ã¼ã¹ã«ããã¾ãã ãã¡ããã覧ãã ããã(https://jstool.gitlab.io/dayjs/ ã使ç¨ãã¦ãã¾ã)
ãã®ç»åã示ãããã«ãç¾å¨ã®dayjsã¯ã'0001-01-01'ãã'0099-12-31'ã¾ã§ã®æååã1900年代ã¨ãã¦è§£éãã¾ãã
JSã®Dateã®ã³ã³ã¹ãã©ã¯ã¿ã§ãYã«2æ¡ã®æ°ã渡ãã¨1900å¹´å°ã¨ãã¦è§£éãããã®ã¯ããããæåãã¨æãã¾ãããdayjsã®å é¨ã§ãããå¼ã³åºãã¦ããããåæ§ã®ç¾è±¡ãèµ·ãã¦ããããã§ããã
Issueã«ããªã£ã¦ãã¾ãããç¾å¨ã¯ä»æ§ã¨ãã¦æ±ããã¦ããããã§ãã
Dateã¨ã¯éã£ã¦"YYYY-MM-DD"
ã§æ¸¡ãã¦ãããã ãã1900年代ãããªãã®ã¯æç½ãããªãããã¨ã¯æãã®ã§ããâ¦ã
ä»çµã¿
ä»æ§ããããã°ãã¨ã¯ç°¡åã§ããå ã»ã©ã®ã1234ãã®ä¾ã§ããªããããªæåã«ãªã£ããé ã追ã£ã¦èãã¦ã¿ã¾ãã
- ãã¼ãã¼ãã§ã1ããæ¼ããæç¹ã§ã
input
ã®ä¸èº«ã¯'0001-01-01'
ã«ãªã£ã¦ãã¾ãã - dayjsã¯ããã
1900å¹´1æ1æ¥
ã¨è§£éããseledtedDate
ã«1900-01-01
ãã»ããããã¾ãã input
ã®ä¸èº«ã'1901-01-01'
ã«ç½®ãæãã£ã¦ãã¾ãããããã©ã¼ã«ã¹ãä¸1æ¡ã«æ»ãã¾ãã- 次ã«ãã¼ãã¼ãã§ã2ããæ¼ãã¨ã
input
ã®ä¸èº«ã¯'0002-01-01'
ã«ãªãã¾ãã(2ã«æ»ã)
ãªãã»ã©ããã§ã¯ããã¤ã¾ã§çµã£ã¦ã2024
ãå
¥åã§ãã¾ãããã
解決
dayjsã«Stringã渡ãã¦ãã¦ã¯ãããããã¾ãããä¸æ¦Date.parse
ã使ã£ã¦ã¨ããã¯ç§ã«ãã¦ãã渡ãã¾ãããã
const parsedDate = dayjs(Date.parse(inputDate));
ããã¨â¦
æ£å¸¸ã«åä½ããç¡äºã«2024å¹´ã«ãªããã¨ãã§ãã¾ããï¼ ããã§å¹²æ¯ãè¾°å¹´ãæ´ãã¦å¹´ç·ã«â¦ã£ã¦ããï¼
1904å¹´ãè¾°å¹´ã ã£ãã®ããåã¯2000å¹´çã¾ãã ããâ¦ãã¤ãã¹96æ³ã£ã¦å¹´ç·ã«ãªãã¾ããï¼
ã¾ã¨ã
input type="date"
ã®ä¸èº«ãdayjs
ã§éä¸ãã¼ã¹ãã¦ããã¨ããã¼ãã¼ãå ¥åããããããªãã(Moment.jsã¯ããã¯ãªããªã)- dayjsã«'0001'å¹´ãã'0099'å¹´ãæ±ã£ã¦æ¬²ããæã¯ãStringã§ã¯ãªãEpochã§æ¸¡ãã¨è¯ããã