ts-time-utils 1.0.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +682 -11
- package/dist/calculate.d.ts +7 -2
- package/dist/calculate.d.ts.map +1 -1
- package/dist/calculate.js +37 -13
- package/dist/calendar.d.ts +103 -0
- package/dist/calendar.d.ts.map +1 -1
- package/dist/calendar.js +224 -0
- package/dist/compare.d.ts +217 -0
- package/dist/compare.d.ts.map +1 -0
- package/dist/compare.js +417 -0
- package/dist/countdown.d.ts +217 -0
- package/dist/countdown.d.ts.map +1 -0
- package/dist/countdown.js +298 -0
- package/dist/cron.d.ts +82 -0
- package/dist/cron.d.ts.map +1 -0
- package/dist/cron.js +294 -0
- package/dist/dateRange.d.ts +266 -0
- package/dist/dateRange.d.ts.map +1 -0
- package/dist/dateRange.js +433 -0
- package/dist/esm/calculate.d.ts +7 -2
- package/dist/esm/calculate.d.ts.map +1 -1
- package/dist/esm/calculate.js +37 -13
- package/dist/esm/calendar.d.ts +103 -0
- package/dist/esm/calendar.d.ts.map +1 -1
- package/dist/esm/calendar.js +224 -0
- package/dist/esm/compare.d.ts +217 -0
- package/dist/esm/compare.d.ts.map +1 -0
- package/dist/esm/compare.js +417 -0
- package/dist/esm/countdown.d.ts +217 -0
- package/dist/esm/countdown.d.ts.map +1 -0
- package/dist/esm/countdown.js +298 -0
- package/dist/esm/cron.d.ts +82 -0
- package/dist/esm/cron.d.ts.map +1 -0
- package/dist/esm/cron.js +294 -0
- package/dist/esm/dateRange.d.ts +266 -0
- package/dist/esm/dateRange.d.ts.map +1 -0
- package/dist/esm/dateRange.js +433 -0
- package/dist/esm/fiscal.d.ts +195 -0
- package/dist/esm/fiscal.d.ts.map +1 -0
- package/dist/esm/fiscal.js +295 -0
- package/dist/esm/format.d.ts +65 -0
- package/dist/esm/format.d.ts.map +1 -1
- package/dist/esm/format.js +202 -0
- package/dist/esm/index.d.ts +18 -7
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +22 -6
- package/dist/esm/iterate.d.ts +212 -0
- package/dist/esm/iterate.d.ts.map +1 -0
- package/dist/esm/iterate.js +409 -0
- package/dist/esm/naturalLanguage.d.ts +107 -0
- package/dist/esm/naturalLanguage.d.ts.map +1 -0
- package/dist/esm/naturalLanguage.js +344 -0
- package/dist/esm/parse.d.ts +45 -0
- package/dist/esm/parse.d.ts.map +1 -1
- package/dist/esm/parse.js +207 -0
- package/dist/esm/recurrence.d.ts +149 -0
- package/dist/esm/recurrence.d.ts.map +1 -0
- package/dist/esm/recurrence.js +404 -0
- package/dist/esm/timezone.d.ts +52 -0
- package/dist/esm/timezone.d.ts.map +1 -1
- package/dist/esm/timezone.js +171 -0
- package/dist/esm/types.d.ts +21 -0
- package/dist/esm/types.d.ts.map +1 -1
- package/dist/esm/validate.d.ts +51 -0
- package/dist/esm/validate.d.ts.map +1 -1
- package/dist/esm/validate.js +92 -0
- package/dist/esm/workingHours.d.ts +70 -0
- package/dist/esm/workingHours.d.ts.map +1 -1
- package/dist/esm/workingHours.js +161 -0
- package/dist/fiscal.d.ts +195 -0
- package/dist/fiscal.d.ts.map +1 -0
- package/dist/fiscal.js +295 -0
- package/dist/format.d.ts +65 -0
- package/dist/format.d.ts.map +1 -1
- package/dist/format.js +202 -0
- package/dist/index.d.ts +18 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +22 -6
- package/dist/iterate.d.ts +212 -0
- package/dist/iterate.d.ts.map +1 -0
- package/dist/iterate.js +409 -0
- package/dist/naturalLanguage.d.ts +107 -0
- package/dist/naturalLanguage.d.ts.map +1 -0
- package/dist/naturalLanguage.js +344 -0
- package/dist/parse.d.ts +45 -0
- package/dist/parse.d.ts.map +1 -1
- package/dist/parse.js +207 -0
- package/dist/recurrence.d.ts +149 -0
- package/dist/recurrence.d.ts.map +1 -0
- package/dist/recurrence.js +404 -0
- package/dist/timezone.d.ts +52 -0
- package/dist/timezone.d.ts.map +1 -1
- package/dist/timezone.js +171 -0
- package/dist/types.d.ts +21 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/validate.d.ts +51 -0
- package/dist/validate.d.ts.map +1 -1
- package/dist/validate.js +92 -0
- package/dist/workingHours.d.ts +70 -0
- package/dist/workingHours.d.ts.map +1 -1
- package/dist/workingHours.js +161 -0
- package/package.json +59 -12
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Natural language date parsing utilities
|
|
3
|
+
* Provides intelligent parsing of human-readable date strings
|
|
4
|
+
*/
|
|
5
|
+
import { addTime } from './calculate.js';
|
|
6
|
+
import { parseRelativeDate } from './parse.js';
|
|
7
|
+
/**
|
|
8
|
+
* Parses natural language date strings into Date objects
|
|
9
|
+
* @param input - Natural language date string
|
|
10
|
+
* @param options - Parsing options
|
|
11
|
+
* @returns Parsed date or null if unable to parse
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* parseNaturalDate('tomorrow at 3pm');
|
|
16
|
+
* // Date for tomorrow at 15:00
|
|
17
|
+
*
|
|
18
|
+
* parseNaturalDate('next Friday');
|
|
19
|
+
* // Date for next Friday
|
|
20
|
+
*
|
|
21
|
+
* parseNaturalDate('in 2 weeks');
|
|
22
|
+
* // Date 2 weeks from now
|
|
23
|
+
*
|
|
24
|
+
* parseNaturalDate('December 25th');
|
|
25
|
+
* // Date for Dec 25 this year (or next if passed)
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export function parseNaturalDate(input, options = {}) {
|
|
29
|
+
const { referenceDate = new Date(), defaultTime } = options;
|
|
30
|
+
const normalized = input.toLowerCase().trim();
|
|
31
|
+
// Try relative phrase parser first (handles "next week", "last month", etc.)
|
|
32
|
+
const relativePhraseResult = parseRelativePhrase(input, referenceDate);
|
|
33
|
+
if (relativePhraseResult)
|
|
34
|
+
return relativePhraseResult;
|
|
35
|
+
// Try existing relative date parser
|
|
36
|
+
const relativeResult = parseRelativeDate(input);
|
|
37
|
+
if (relativeResult)
|
|
38
|
+
return relativeResult;
|
|
39
|
+
// Common absolute patterns
|
|
40
|
+
const absolutePatterns = [
|
|
41
|
+
// "next Friday", "last Monday"
|
|
42
|
+
/^(next|last|this)\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/,
|
|
43
|
+
// "Friday", "Monday" (interpreted as next occurrence)
|
|
44
|
+
/^(monday|tuesday|wednesday|thursday|friday|saturday|sunday)$/,
|
|
45
|
+
// "tomorrow at 3pm", "today at noon"
|
|
46
|
+
/^(today|tomorrow|yesterday)\s+at\s+(.+)$/,
|
|
47
|
+
// "3pm today", "noon tomorrow"
|
|
48
|
+
/^(.+?)\s+(today|tomorrow|yesterday)$/,
|
|
49
|
+
// "in 2 weeks", "in 3 days"
|
|
50
|
+
/^in\s+(\d+)\s+(minute|minutes|hour|hours|day|days|week|weeks|month|months|year|years)$/,
|
|
51
|
+
// "2 weeks from now", "3 days ago"
|
|
52
|
+
/^(\d+)\s+(minute|minutes|hour|hours|day|days|week|weeks|month|months|year|years)\s+(from now|ago)$/,
|
|
53
|
+
// "December 25", "Dec 25", "25 December"
|
|
54
|
+
/^(january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+(\d{1,2})(st|nd|rd|th)?$/,
|
|
55
|
+
/^(\d{1,2})(st|nd|rd|th)?\s+(january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)$/,
|
|
56
|
+
];
|
|
57
|
+
// Check each pattern
|
|
58
|
+
for (const pattern of absolutePatterns) {
|
|
59
|
+
const match = normalized.match(pattern);
|
|
60
|
+
if (match) {
|
|
61
|
+
return parseMatchedPattern(match, referenceDate, defaultTime);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// Try standard Date parsing as fallback
|
|
65
|
+
const standardDate = new Date(input);
|
|
66
|
+
if (!isNaN(standardDate.getTime())) {
|
|
67
|
+
return standardDate;
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Parses a relative time phrase into a Date
|
|
73
|
+
* @param input - Relative time phrase
|
|
74
|
+
* @param referenceDate - Reference date (defaults to now)
|
|
75
|
+
* @returns Parsed date or null
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
* ```ts
|
|
79
|
+
* parseRelativePhrase('in 2 hours'); // 2 hours from now
|
|
80
|
+
* parseRelativePhrase('5 minutes ago'); // 5 minutes ago
|
|
81
|
+
* parseRelativePhrase('next week'); // 7 days from now
|
|
82
|
+
* ```
|
|
83
|
+
*/
|
|
84
|
+
export function parseRelativePhrase(input, referenceDate = new Date()) {
|
|
85
|
+
const normalized = input.toLowerCase().trim();
|
|
86
|
+
// "in X units"
|
|
87
|
+
const inPattern = /^in\s+(\d+)\s+(millisecond|milliseconds|second|seconds|minute|minutes|hour|hours|day|days|week|weeks|month|months|year|years)$/;
|
|
88
|
+
let match = normalized.match(inPattern);
|
|
89
|
+
if (match) {
|
|
90
|
+
const amount = parseInt(match[1], 10);
|
|
91
|
+
const unit = normalizeUnit(match[2]);
|
|
92
|
+
return addTime(referenceDate, amount, unit);
|
|
93
|
+
}
|
|
94
|
+
// "X units ago"
|
|
95
|
+
const agoPattern = /^(\d+)\s+(millisecond|milliseconds|second|seconds|minute|minutes|hour|hours|day|days|week|weeks|month|months|year|years)\s+ago$/;
|
|
96
|
+
match = normalized.match(agoPattern);
|
|
97
|
+
if (match) {
|
|
98
|
+
const amount = parseInt(match[1], 10);
|
|
99
|
+
const unit = normalizeUnit(match[2]);
|
|
100
|
+
return addTime(referenceDate, -amount, unit);
|
|
101
|
+
}
|
|
102
|
+
// "X units from now"
|
|
103
|
+
const fromNowPattern = /^(\d+)\s+(millisecond|milliseconds|second|seconds|minute|minutes|hour|hours|day|days|week|weeks|month|months|year|years)\s+from\s+now$/;
|
|
104
|
+
match = normalized.match(fromNowPattern);
|
|
105
|
+
if (match) {
|
|
106
|
+
const amount = parseInt(match[1], 10);
|
|
107
|
+
const unit = normalizeUnit(match[2]);
|
|
108
|
+
return addTime(referenceDate, amount, unit);
|
|
109
|
+
}
|
|
110
|
+
// Common shortcuts - use switch/case to properly use the referenceDate parameter
|
|
111
|
+
switch (normalized) {
|
|
112
|
+
case 'now':
|
|
113
|
+
return new Date(referenceDate);
|
|
114
|
+
case 'today': {
|
|
115
|
+
const d = new Date(referenceDate);
|
|
116
|
+
d.setHours(0, 0, 0, 0);
|
|
117
|
+
return d;
|
|
118
|
+
}
|
|
119
|
+
case 'tomorrow':
|
|
120
|
+
return addTime(referenceDate, 1, 'day');
|
|
121
|
+
case 'yesterday':
|
|
122
|
+
return addTime(referenceDate, -1, 'day');
|
|
123
|
+
case 'next week':
|
|
124
|
+
return addTime(referenceDate, 1, 'week');
|
|
125
|
+
case 'last week':
|
|
126
|
+
return addTime(referenceDate, -1, 'week');
|
|
127
|
+
case 'next month':
|
|
128
|
+
return addTime(referenceDate, 1, 'month');
|
|
129
|
+
case 'last month':
|
|
130
|
+
return addTime(referenceDate, -1, 'month');
|
|
131
|
+
case 'next year':
|
|
132
|
+
return addTime(referenceDate, 1, 'year');
|
|
133
|
+
case 'last year':
|
|
134
|
+
return addTime(referenceDate, -1, 'year');
|
|
135
|
+
default:
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Extracts all dates from a text string
|
|
141
|
+
* @param text - Text to extract dates from
|
|
142
|
+
* @param options - Extraction options
|
|
143
|
+
* @returns Array of extracted date information
|
|
144
|
+
*
|
|
145
|
+
* @example
|
|
146
|
+
* ```ts
|
|
147
|
+
* const text = "Meeting tomorrow at 3pm and dinner next Friday at 7pm";
|
|
148
|
+
* const dates = extractDatesFromText(text);
|
|
149
|
+
* // [
|
|
150
|
+
* // { date: Date(...), text: 'tomorrow at 3pm', index: 8, ... },
|
|
151
|
+
* // { date: Date(...), text: 'next Friday at 7pm', index: 37, ... }
|
|
152
|
+
* // ]
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
155
|
+
export function extractDatesFromText(text, options = {}) {
|
|
156
|
+
const { referenceDate = new Date() } = options;
|
|
157
|
+
const results = [];
|
|
158
|
+
// Patterns to match
|
|
159
|
+
const patterns = [
|
|
160
|
+
// Relative dates
|
|
161
|
+
/\b(tomorrow|yesterday|today)\b/gi,
|
|
162
|
+
/\b(next|last|this)\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday|week|month|year)\b/gi,
|
|
163
|
+
/\bin\s+\d+\s+(minute|minutes|hour|hours|day|days|week|weeks|month|months|year|years)\b/gi,
|
|
164
|
+
/\b\d+\s+(minute|minutes|hour|hours|day|days|week|weeks|month|months|year|years)\s+(ago|from now)\b/gi,
|
|
165
|
+
// Absolute dates
|
|
166
|
+
/\b(january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+\d{1,2}(st|nd|rd|th)?\b/gi,
|
|
167
|
+
/\b\d{1,2}(st|nd|rd|th)?\s+(of\s+)?(january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\b/gi,
|
|
168
|
+
// Date formats
|
|
169
|
+
/\b\d{1,2}[\/\-\.]\d{1,2}[\/\-\.]\d{2,4}\b/g,
|
|
170
|
+
/\b\d{4}[\/\-\.]\d{1,2}[\/\-\.]\d{1,2}\b/g,
|
|
171
|
+
// Time patterns (when found with dates)
|
|
172
|
+
/\bat\s+\d{1,2}(:\d{2})?\s*(am|pm|AM|PM)?\b/gi,
|
|
173
|
+
];
|
|
174
|
+
const processed = new Set();
|
|
175
|
+
for (const pattern of patterns) {
|
|
176
|
+
let match;
|
|
177
|
+
while ((match = pattern.exec(text)) !== null) {
|
|
178
|
+
const matchedText = match[0];
|
|
179
|
+
const index = match.index;
|
|
180
|
+
// Skip if already processed
|
|
181
|
+
if (processed.has(`${index}-${matchedText}`))
|
|
182
|
+
continue;
|
|
183
|
+
processed.add(`${index}-${matchedText}`);
|
|
184
|
+
// Try to parse the matched text
|
|
185
|
+
const parsed = parseNaturalDate(matchedText, { referenceDate });
|
|
186
|
+
if (parsed) {
|
|
187
|
+
results.push({
|
|
188
|
+
date: parsed,
|
|
189
|
+
text: matchedText,
|
|
190
|
+
index,
|
|
191
|
+
type: determineType(matchedText),
|
|
192
|
+
confidence: calculateConfidence(matchedText)
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
// Sort by index (order in text)
|
|
198
|
+
return results.sort((a, b) => a.index - b.index);
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Suggests possible dates based on context
|
|
202
|
+
* @param context - Context string to analyze
|
|
203
|
+
* @param options - Parsing options
|
|
204
|
+
* @returns Array of suggested dates with confidence scores
|
|
205
|
+
*
|
|
206
|
+
* @example
|
|
207
|
+
* ```ts
|
|
208
|
+
* suggestDateFromContext('deadline is end of month');
|
|
209
|
+
* // [{ date: Date(last day of current month), confidence: 0.8, ... }]
|
|
210
|
+
* ```
|
|
211
|
+
*/
|
|
212
|
+
export function suggestDateFromContext(context, options = {}) {
|
|
213
|
+
const { referenceDate = new Date() } = options;
|
|
214
|
+
const suggestions = [];
|
|
215
|
+
const normalized = context.toLowerCase();
|
|
216
|
+
// End of month
|
|
217
|
+
if (normalized.includes('end of month') || normalized.includes('eom')) {
|
|
218
|
+
const date = new Date(referenceDate.getFullYear(), referenceDate.getMonth() + 1, 0);
|
|
219
|
+
suggestions.push({ date, text: 'end of month', confidence: 0.85 });
|
|
220
|
+
}
|
|
221
|
+
// Beginning of month
|
|
222
|
+
if (normalized.includes('beginning of month') || normalized.includes('start of month')) {
|
|
223
|
+
const date = new Date(referenceDate.getFullYear(), referenceDate.getMonth(), 1);
|
|
224
|
+
suggestions.push({ date, text: 'beginning of month', confidence: 0.85 });
|
|
225
|
+
}
|
|
226
|
+
// End of year
|
|
227
|
+
if (normalized.includes('end of year') || normalized.includes('eoy')) {
|
|
228
|
+
const date = new Date(referenceDate.getFullYear(), 11, 31);
|
|
229
|
+
suggestions.push({ date, text: 'end of year', confidence: 0.85 });
|
|
230
|
+
}
|
|
231
|
+
// Beginning of year
|
|
232
|
+
if (normalized.includes('beginning of year') || normalized.includes('start of year')) {
|
|
233
|
+
const date = new Date(referenceDate.getFullYear(), 0, 1);
|
|
234
|
+
suggestions.push({ date, text: 'beginning of year', confidence: 0.85 });
|
|
235
|
+
}
|
|
236
|
+
// End of week
|
|
237
|
+
if (normalized.includes('end of week') || normalized.includes('eow')) {
|
|
238
|
+
const date = new Date(referenceDate);
|
|
239
|
+
const day = date.getDay();
|
|
240
|
+
const diff = 6 - day; // Saturday
|
|
241
|
+
date.setDate(date.getDate() + diff);
|
|
242
|
+
suggestions.push({ date, text: 'end of week', confidence: 0.85 });
|
|
243
|
+
}
|
|
244
|
+
// Extract any explicit dates
|
|
245
|
+
const extracted = extractDatesFromText(context, options);
|
|
246
|
+
for (const item of extracted) {
|
|
247
|
+
suggestions.push({
|
|
248
|
+
date: item.date,
|
|
249
|
+
text: item.text,
|
|
250
|
+
confidence: item.confidence
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
// Sort by confidence
|
|
254
|
+
return suggestions.sort((a, b) => b.confidence - a.confidence);
|
|
255
|
+
}
|
|
256
|
+
// Helper functions
|
|
257
|
+
function parseMatchedPattern(match, referenceDate, defaultTime) {
|
|
258
|
+
const pattern = match[0];
|
|
259
|
+
// Weekday patterns
|
|
260
|
+
if (pattern.includes('monday') || pattern.includes('tuesday') ||
|
|
261
|
+
pattern.includes('wednesday') || pattern.includes('thursday') ||
|
|
262
|
+
pattern.includes('friday') || pattern.includes('saturday') ||
|
|
263
|
+
pattern.includes('sunday')) {
|
|
264
|
+
const weekdayMap = {
|
|
265
|
+
'sunday': 0, 'monday': 1, 'tuesday': 2, 'wednesday': 3,
|
|
266
|
+
'thursday': 4, 'friday': 5, 'saturday': 6
|
|
267
|
+
};
|
|
268
|
+
const weekday = Object.keys(weekdayMap).find(day => pattern.includes(day));
|
|
269
|
+
if (!weekday)
|
|
270
|
+
return null;
|
|
271
|
+
const targetDay = weekdayMap[weekday];
|
|
272
|
+
const currentDay = referenceDate.getDay();
|
|
273
|
+
let daysToAdd = targetDay - currentDay;
|
|
274
|
+
if (pattern.includes('next')) {
|
|
275
|
+
if (daysToAdd <= 0)
|
|
276
|
+
daysToAdd += 7;
|
|
277
|
+
}
|
|
278
|
+
else if (pattern.includes('last')) {
|
|
279
|
+
if (daysToAdd >= 0)
|
|
280
|
+
daysToAdd -= 7;
|
|
281
|
+
}
|
|
282
|
+
else {
|
|
283
|
+
// "this" or just the weekday name - go to next occurrence
|
|
284
|
+
if (daysToAdd <= 0)
|
|
285
|
+
daysToAdd += 7;
|
|
286
|
+
}
|
|
287
|
+
return addTime(referenceDate, daysToAdd, 'day');
|
|
288
|
+
}
|
|
289
|
+
// "in X units" pattern
|
|
290
|
+
if (match[1] && match[2]) {
|
|
291
|
+
const amount = parseInt(match[1], 10);
|
|
292
|
+
const unit = normalizeUnit(match[2]);
|
|
293
|
+
if (match[3] === 'ago') {
|
|
294
|
+
return addTime(referenceDate, -amount, unit);
|
|
295
|
+
}
|
|
296
|
+
return addTime(referenceDate, amount, unit);
|
|
297
|
+
}
|
|
298
|
+
return null;
|
|
299
|
+
}
|
|
300
|
+
function normalizeUnit(unit) {
|
|
301
|
+
const normalized = unit.toLowerCase().replace(/s$/, '');
|
|
302
|
+
switch (normalized) {
|
|
303
|
+
case 'millisecond': return 'millisecond';
|
|
304
|
+
case 'second': return 'second';
|
|
305
|
+
case 'minute': return 'minute';
|
|
306
|
+
case 'hour': return 'hour';
|
|
307
|
+
case 'day': return 'day';
|
|
308
|
+
case 'week': return 'week';
|
|
309
|
+
case 'month': return 'month';
|
|
310
|
+
case 'year': return 'year';
|
|
311
|
+
default: return 'day';
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
function determineType(text) {
|
|
315
|
+
const lower = text.toLowerCase();
|
|
316
|
+
if (lower.includes('ago') || lower.includes('from now') || lower.includes('in ')) {
|
|
317
|
+
return 'relative';
|
|
318
|
+
}
|
|
319
|
+
if (lower.includes('to') || lower.includes(' - ') || lower.includes('between')) {
|
|
320
|
+
return 'range';
|
|
321
|
+
}
|
|
322
|
+
if (lower.includes('at ') || lower.includes('am') || lower.includes('pm') || /\d{1,2}:\d{2}/.test(lower)) {
|
|
323
|
+
return 'time';
|
|
324
|
+
}
|
|
325
|
+
return 'absolute';
|
|
326
|
+
}
|
|
327
|
+
function calculateConfidence(text) {
|
|
328
|
+
const lower = text.toLowerCase();
|
|
329
|
+
let confidence = 0.5; // Base confidence
|
|
330
|
+
// Higher confidence for specific patterns
|
|
331
|
+
if (lower.includes('tomorrow') || lower.includes('yesterday') || lower.includes('today')) {
|
|
332
|
+
confidence += 0.4;
|
|
333
|
+
}
|
|
334
|
+
if (/\d{4}/.test(text)) { // Has year
|
|
335
|
+
confidence += 0.2;
|
|
336
|
+
}
|
|
337
|
+
if (/\d{1,2}:\d{2}/.test(text)) { // Has time
|
|
338
|
+
confidence += 0.15;
|
|
339
|
+
}
|
|
340
|
+
if (lower.includes('next') || lower.includes('last')) {
|
|
341
|
+
confidence += 0.1;
|
|
342
|
+
}
|
|
343
|
+
return Math.min(1.0, confidence);
|
|
344
|
+
}
|
package/dist/esm/parse.d.ts
CHANGED
|
@@ -28,4 +28,49 @@ export declare function parseCustomFormat(dateString: string, format: string): D
|
|
|
28
28
|
* @param formats - array of format patterns to try
|
|
29
29
|
*/
|
|
30
30
|
export declare function parseManyFormats(dateString: string, formats: string[]): Date | null;
|
|
31
|
+
/**
|
|
32
|
+
* Parse an ISO 8601 duration string (e.g., "P1Y2M3DT4H5M6S")
|
|
33
|
+
* @param duration - ISO 8601 duration string
|
|
34
|
+
* @returns object with parsed components
|
|
35
|
+
*/
|
|
36
|
+
export declare function parseISO8601Duration(duration: string): {
|
|
37
|
+
years: number;
|
|
38
|
+
months: number;
|
|
39
|
+
weeks: number;
|
|
40
|
+
days: number;
|
|
41
|
+
hours: number;
|
|
42
|
+
minutes: number;
|
|
43
|
+
seconds: number;
|
|
44
|
+
} | null;
|
|
45
|
+
/**
|
|
46
|
+
* Convert ISO 8601 duration to milliseconds (approximate for months/years)
|
|
47
|
+
* @param duration - ISO 8601 duration string
|
|
48
|
+
*/
|
|
49
|
+
export declare function parseISO8601DurationToMs(duration: string): number | null;
|
|
50
|
+
/**
|
|
51
|
+
* Parse a time string (e.g., "14:30", "2:30 PM", "14:30:45")
|
|
52
|
+
* @param timeString - time string to parse
|
|
53
|
+
* @returns object with hours, minutes, seconds, or null if invalid
|
|
54
|
+
*/
|
|
55
|
+
export declare function parseTime(timeString: string): {
|
|
56
|
+
hours: number;
|
|
57
|
+
minutes: number;
|
|
58
|
+
seconds: number;
|
|
59
|
+
} | null;
|
|
60
|
+
/**
|
|
61
|
+
* Guess the date format of a date string
|
|
62
|
+
* @param dateString - date string to analyze
|
|
63
|
+
* @returns detected format pattern or null
|
|
64
|
+
*/
|
|
65
|
+
export declare function guessDateFormat(dateString: string): string | null;
|
|
66
|
+
/**
|
|
67
|
+
* Parse a date string using auto-detected format
|
|
68
|
+
* @param dateString - date string to parse
|
|
69
|
+
*/
|
|
70
|
+
export declare function parseAutoFormat(dateString: string): Date | null;
|
|
71
|
+
/**
|
|
72
|
+
* Parse a date from a natural language date range endpoint
|
|
73
|
+
* @param input - string like "end of month", "start of year", "beginning of week"
|
|
74
|
+
*/
|
|
75
|
+
export declare function parseRangeEndpoint(input: string): Date | null;
|
|
31
76
|
//# sourceMappingURL=parse.d.ts.map
|
package/dist/esm/parse.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse.d.ts","sourceRoot":"","sources":["../../src/parse.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;GAGG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,CAuDpE;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CA6C5D;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAiBvD;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAmDjF;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,GAAG,IAAI,CAMnF"}
|
|
1
|
+
{"version":3,"file":"parse.d.ts","sourceRoot":"","sources":["../../src/parse.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;GAGG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,CAuDpE;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CA6C5D;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAiBvD;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAmDjF;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,GAAG,IAAI,CAMnF;AAqCD;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,GAAG;IACtD,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB,GAAG,IAAI,CA4CP;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAqBxE;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG;IAC7C,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB,GAAG,IAAI,CAuCP;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAoCjE;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAmB/D;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CA2C7D"}
|
package/dist/esm/parse.js
CHANGED
|
@@ -215,3 +215,210 @@ function addTimeUnits(date, amount, unit) {
|
|
|
215
215
|
function subtractTimeUnits(date, amount, unit) {
|
|
216
216
|
return addTimeUnits(date, -amount, unit);
|
|
217
217
|
}
|
|
218
|
+
/**
|
|
219
|
+
* Parse an ISO 8601 duration string (e.g., "P1Y2M3DT4H5M6S")
|
|
220
|
+
* @param duration - ISO 8601 duration string
|
|
221
|
+
* @returns object with parsed components
|
|
222
|
+
*/
|
|
223
|
+
export function parseISO8601Duration(duration) {
|
|
224
|
+
// ISO 8601 duration format: P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W
|
|
225
|
+
const result = {
|
|
226
|
+
years: 0,
|
|
227
|
+
months: 0,
|
|
228
|
+
weeks: 0,
|
|
229
|
+
days: 0,
|
|
230
|
+
hours: 0,
|
|
231
|
+
minutes: 0,
|
|
232
|
+
seconds: 0,
|
|
233
|
+
};
|
|
234
|
+
const normalized = duration.toUpperCase().trim();
|
|
235
|
+
if (!normalized.startsWith('P')) {
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
// Handle week format: P[n]W
|
|
239
|
+
const weekMatch = normalized.match(/^P(\d+)W$/);
|
|
240
|
+
if (weekMatch) {
|
|
241
|
+
result.weeks = parseInt(weekMatch[1]);
|
|
242
|
+
return result;
|
|
243
|
+
}
|
|
244
|
+
// Full format: P[n]Y[n]M[n]DT[n]H[n]M[n]S
|
|
245
|
+
const fullMatch = normalized.match(/^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/);
|
|
246
|
+
if (!fullMatch) {
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
249
|
+
const [, years, months, days, hours, minutes, seconds] = fullMatch;
|
|
250
|
+
if (years)
|
|
251
|
+
result.years = parseInt(years);
|
|
252
|
+
if (months)
|
|
253
|
+
result.months = parseInt(months);
|
|
254
|
+
if (days)
|
|
255
|
+
result.days = parseInt(days);
|
|
256
|
+
if (hours)
|
|
257
|
+
result.hours = parseInt(hours);
|
|
258
|
+
if (minutes)
|
|
259
|
+
result.minutes = parseInt(minutes);
|
|
260
|
+
if (seconds)
|
|
261
|
+
result.seconds = parseFloat(seconds);
|
|
262
|
+
return result;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Convert ISO 8601 duration to milliseconds (approximate for months/years)
|
|
266
|
+
* @param duration - ISO 8601 duration string
|
|
267
|
+
*/
|
|
268
|
+
export function parseISO8601DurationToMs(duration) {
|
|
269
|
+
const parsed = parseISO8601Duration(duration);
|
|
270
|
+
if (!parsed)
|
|
271
|
+
return null;
|
|
272
|
+
const MS_PER_SECOND = 1000;
|
|
273
|
+
const MS_PER_MINUTE = 60 * MS_PER_SECOND;
|
|
274
|
+
const MS_PER_HOUR = 60 * MS_PER_MINUTE;
|
|
275
|
+
const MS_PER_DAY = 24 * MS_PER_HOUR;
|
|
276
|
+
const MS_PER_WEEK = 7 * MS_PER_DAY;
|
|
277
|
+
const MS_PER_MONTH = 30 * MS_PER_DAY; // Approximate
|
|
278
|
+
const MS_PER_YEAR = 365 * MS_PER_DAY; // Approximate
|
|
279
|
+
return (parsed.years * MS_PER_YEAR +
|
|
280
|
+
parsed.months * MS_PER_MONTH +
|
|
281
|
+
parsed.weeks * MS_PER_WEEK +
|
|
282
|
+
parsed.days * MS_PER_DAY +
|
|
283
|
+
parsed.hours * MS_PER_HOUR +
|
|
284
|
+
parsed.minutes * MS_PER_MINUTE +
|
|
285
|
+
parsed.seconds * MS_PER_SECOND);
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Parse a time string (e.g., "14:30", "2:30 PM", "14:30:45")
|
|
289
|
+
* @param timeString - time string to parse
|
|
290
|
+
* @returns object with hours, minutes, seconds, or null if invalid
|
|
291
|
+
*/
|
|
292
|
+
export function parseTime(timeString) {
|
|
293
|
+
const normalized = timeString.trim();
|
|
294
|
+
// 24-hour format: HH:MM or HH:MM:SS
|
|
295
|
+
const match24 = normalized.match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/);
|
|
296
|
+
if (match24) {
|
|
297
|
+
const hours = parseInt(match24[1]);
|
|
298
|
+
const minutes = parseInt(match24[2]);
|
|
299
|
+
const seconds = match24[3] ? parseInt(match24[3]) : 0;
|
|
300
|
+
if (hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59 && seconds >= 0 && seconds <= 59) {
|
|
301
|
+
return { hours, minutes, seconds };
|
|
302
|
+
}
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
// 12-hour format: H:MM AM/PM or HH:MM AM/PM
|
|
306
|
+
const match12 = normalized.match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?\s*(AM|PM|am|pm)$/i);
|
|
307
|
+
if (match12) {
|
|
308
|
+
let hours = parseInt(match12[1]);
|
|
309
|
+
const minutes = parseInt(match12[2]);
|
|
310
|
+
const seconds = match12[3] ? parseInt(match12[3]) : 0;
|
|
311
|
+
const isPM = match12[4].toLowerCase() === 'pm';
|
|
312
|
+
if (hours < 1 || hours > 12 || minutes < 0 || minutes > 59 || seconds < 0 || seconds > 59) {
|
|
313
|
+
return null;
|
|
314
|
+
}
|
|
315
|
+
// Convert to 24-hour format
|
|
316
|
+
if (isPM && hours !== 12) {
|
|
317
|
+
hours += 12;
|
|
318
|
+
}
|
|
319
|
+
else if (!isPM && hours === 12) {
|
|
320
|
+
hours = 0;
|
|
321
|
+
}
|
|
322
|
+
return { hours, minutes, seconds };
|
|
323
|
+
}
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Guess the date format of a date string
|
|
328
|
+
* @param dateString - date string to analyze
|
|
329
|
+
* @returns detected format pattern or null
|
|
330
|
+
*/
|
|
331
|
+
export function guessDateFormat(dateString) {
|
|
332
|
+
const normalized = dateString.trim();
|
|
333
|
+
// YYYY-MM-DD
|
|
334
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) {
|
|
335
|
+
return 'YYYY-MM-DD';
|
|
336
|
+
}
|
|
337
|
+
// DD/MM/YYYY or MM/DD/YYYY - need to analyze values
|
|
338
|
+
if (/^\d{2}\/\d{2}\/\d{4}$/.test(normalized)) {
|
|
339
|
+
const [first, second] = normalized.split('/').map(Number);
|
|
340
|
+
if (first > 12)
|
|
341
|
+
return 'DD/MM/YYYY'; // First must be day
|
|
342
|
+
if (second > 12)
|
|
343
|
+
return 'MM/DD/YYYY'; // Second must be day
|
|
344
|
+
// Ambiguous - default to US format
|
|
345
|
+
return 'MM/DD/YYYY';
|
|
346
|
+
}
|
|
347
|
+
// DD-MM-YYYY or MM-DD-YYYY
|
|
348
|
+
if (/^\d{2}-\d{2}-\d{4}$/.test(normalized)) {
|
|
349
|
+
const [first, second] = normalized.split('-').map(Number);
|
|
350
|
+
if (first > 12)
|
|
351
|
+
return 'DD-MM-YYYY';
|
|
352
|
+
if (second > 12)
|
|
353
|
+
return 'MM-DD-YYYY';
|
|
354
|
+
return 'MM-DD-YYYY';
|
|
355
|
+
}
|
|
356
|
+
// YYYYMMDD
|
|
357
|
+
if (/^\d{8}$/.test(normalized)) {
|
|
358
|
+
return 'YYYYMMDD';
|
|
359
|
+
}
|
|
360
|
+
// ISO 8601 with time
|
|
361
|
+
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(normalized)) {
|
|
362
|
+
return 'ISO8601';
|
|
363
|
+
}
|
|
364
|
+
return null;
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Parse a date string using auto-detected format
|
|
368
|
+
* @param dateString - date string to parse
|
|
369
|
+
*/
|
|
370
|
+
export function parseAutoFormat(dateString) {
|
|
371
|
+
const format = guessDateFormat(dateString);
|
|
372
|
+
if (!format) {
|
|
373
|
+
return parseDate(dateString);
|
|
374
|
+
}
|
|
375
|
+
if (format === 'ISO8601') {
|
|
376
|
+
return parseDate(dateString);
|
|
377
|
+
}
|
|
378
|
+
if (format === 'YYYYMMDD') {
|
|
379
|
+
const year = parseInt(dateString.slice(0, 4));
|
|
380
|
+
const month = parseInt(dateString.slice(4, 6)) - 1;
|
|
381
|
+
const day = parseInt(dateString.slice(6, 8));
|
|
382
|
+
return new Date(year, month, day);
|
|
383
|
+
}
|
|
384
|
+
return parseCustomFormat(dateString, format);
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Parse a date from a natural language date range endpoint
|
|
388
|
+
* @param input - string like "end of month", "start of year", "beginning of week"
|
|
389
|
+
*/
|
|
390
|
+
export function parseRangeEndpoint(input) {
|
|
391
|
+
const now = new Date();
|
|
392
|
+
const lowercaseInput = input.toLowerCase().trim();
|
|
393
|
+
// Start/beginning of period
|
|
394
|
+
if (lowercaseInput.match(/^(start|beginning)\s+of\s+(this\s+)?(day|today)$/)) {
|
|
395
|
+
return new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
|
|
396
|
+
}
|
|
397
|
+
if (lowercaseInput.match(/^(start|beginning)\s+of\s+(this\s+)?week$/)) {
|
|
398
|
+
const day = now.getDay();
|
|
399
|
+
const diff = now.getDate() - day + (day === 0 ? -6 : 1); // Monday
|
|
400
|
+
return new Date(now.getFullYear(), now.getMonth(), diff, 0, 0, 0, 0);
|
|
401
|
+
}
|
|
402
|
+
if (lowercaseInput.match(/^(start|beginning)\s+of\s+(this\s+)?month$/)) {
|
|
403
|
+
return new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0, 0);
|
|
404
|
+
}
|
|
405
|
+
if (lowercaseInput.match(/^(start|beginning)\s+of\s+(this\s+)?year$/)) {
|
|
406
|
+
return new Date(now.getFullYear(), 0, 1, 0, 0, 0, 0);
|
|
407
|
+
}
|
|
408
|
+
// End of period
|
|
409
|
+
if (lowercaseInput.match(/^end\s+of\s+(this\s+)?(day|today)$/)) {
|
|
410
|
+
return new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);
|
|
411
|
+
}
|
|
412
|
+
if (lowercaseInput.match(/^end\s+of\s+(this\s+)?week$/)) {
|
|
413
|
+
const day = now.getDay();
|
|
414
|
+
const diff = now.getDate() - day + (day === 0 ? 0 : 7); // Sunday
|
|
415
|
+
return new Date(now.getFullYear(), now.getMonth(), diff, 23, 59, 59, 999);
|
|
416
|
+
}
|
|
417
|
+
if (lowercaseInput.match(/^end\s+of\s+(this\s+)?month$/)) {
|
|
418
|
+
return new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59, 999);
|
|
419
|
+
}
|
|
420
|
+
if (lowercaseInput.match(/^end\s+of\s+(this\s+)?year$/)) {
|
|
421
|
+
return new Date(now.getFullYear(), 11, 31, 23, 59, 59, 999);
|
|
422
|
+
}
|
|
423
|
+
return null;
|
|
424
|
+
}
|