# NOTE系統日期計算語法
當輸入日期,後面加個 `=`

按下「計算日期差距」,即得到以下結果

## Claude Link
https://claude.site/artifacts/e676e85f-61e7-4dca-a1e9-f39562ee3605
## Code
```javascript
import React, { useState } from 'react';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
const DateDurationInput = () => {
const [text, setText] = useState('');
const isValidDate = (dateStr) => {
const [year, month, day] = dateStr.split('-').map(num => parseInt(num, 10));
const date = new Date(year, month - 1, day);
return date.getFullYear() === year &&
date.getMonth() === month - 1 &&
date.getDate() === day;
};
const calculateDaysDifference = (targetDate) => {
const today = new Date();
today.setHours(0, 0, 0, 0);
const target = new Date(targetDate);
target.setHours(0, 0, 0, 0);
const diffTime = target - today;
const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
return diffDays;
};
const parseDateString = (dateStr) => {
const currentYear = new Date().getFullYear();
let formattedDate = dateStr;
if (dateStr.length <= 5) {
formattedDate = `${currentYear}-${dateStr.replace('/', '-')}`;
}
formattedDate = formattedDate.replace(/\//g, '-');
const parts = formattedDate.split('-');
if (parts.length === 3) {
formattedDate = `${parts[0]}-${parts[1].padStart(2, '0')}-${parts[2].padStart(2, '0')}`;
}
return formattedDate;
};
const handleCalculate = () => {
const datePattern = /(\d{4}[-/]\d{1,2}[-/]\d{1,2}|\d{1,2}[-/]\d{1,2})=/g;
let match;
let processedText = text;
let matches = [];
while ((match = datePattern.exec(text)) !== null) {
matches.push({
fullMatch: match[0],
dateStr: match[1],
index: match.index
});
}
for (let i = matches.length - 1; i >= 0; i--) {
const { fullMatch, dateStr, index } = matches[i];
const formattedDate = parseDateString(dateStr);
if (isValidDate(formattedDate)) {
const daysDiff = calculateDaysDifference(formattedDate);
const relativeText = daysDiff === 0
? 'today'
: `${Math.abs(daysDiff)} days ${daysDiff > 0 ? 'later' : 'ago'}`;
const resultDate = dateStr.includes('/') ? dateStr.replace(/-/g, '/') : dateStr;
const replacement = `${resultDate} (${relativeText})`;
processedText =
processedText.substring(0, index) +
replacement +
processedText.substring(index + fullMatch.length);
}
}
setText(processedText);
};
return (
<div className="h-screen flex items-center justify-center bg-gray-50">
<div className="w-full max-w-md space-y-4 bg-white p-6 rounded-lg shadow-md">
<div className="flex flex-col gap-4">
<Textarea
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="請輸入文字 (例如: Patient will return on 12/31=)"
className="min-h-[120px] text-lg"
/>
<Button
onClick={handleCalculate}
className="w-full"
>
計算日期差距
</Button>
</div>
<div className="text-sm text-gray-500">
支援格式:
<ul className="list-disc pl-5 mt-1">
<li>11/23=</li>
<li>2024-11-23=</li>
<li>11-23=</li>
</ul>
</div>
</div>
</div>
);
};
export default DateDurationInput;
```