@stacksjs/datetime 0.75.423 → 0.75.431

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 CHANGED
@@ -11,6 +11,10 @@ Easily work with dates. Zero external dependencies, Carbon-inspired API.
11
11
  - Modify dates with ease (immutable operations)
12
12
  - Zero external dependencies
13
13
 
14
+ Date-only ISO strings use local midnight consistently in `parse`, `format`, and `DateTime`. Explicit offsets continue to describe instants. Years `0000` through `0099` retain their literal year in parsing, construction, and period boundaries. Format punctuation is matched literally when parsing. An omitted `DateTime` input means now; empty strings and invalid dates throw.
15
+
16
+ Formatted parsing validates calendar dates, clock components, and timezone offsets instead of normalizing impossible input. Pass the locale as the third argument to parse localized long or short month names, for example `parse('15 März 2024', 'D MMMM YYYY', 'de')`.
17
+
14
18
  ## Usage
15
19
 
16
20
  ```bash
package/dist/calendar.js CHANGED
@@ -1 +1 @@
1
- import{zonedTimeToUtc}from"./zone";export function addCalendarMonths(date,months,options={}){if(!Number.isFinite(date.getTime())||!Number.isSafeInteger(months))throw Error("Calendar arithmetic requires a valid date and integer month count");const result=new Date(date);if(options.utc){const day=result.getUTCDate();result.setUTCDate(1);result.setUTCMonth(result.getUTCMonth()+months);result.setUTCDate(Math.min(day,new Date(Date.UTC(result.getUTCFullYear(),result.getUTCMonth()+1,0)).getUTCDate()))}else{const day=result.getDate();result.setDate(1);result.setMonth(result.getMonth()+months);result.setDate(Math.min(day,new Date(result.getFullYear(),result.getMonth()+1,0).getDate()))}return result}const DAY_MS=86400000,YMD=/^\d{4}-\d{2}-\d{2}$/,CLOCK=/^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/;export function isCalendarDate(value){if(typeof value!=="string"||!YMD.test(value))return!1;const time=Date.parse(`${value}T00:00:00Z`);return Number.isFinite(time)&&new Date(time).toISOString().slice(0,10)===value}export function isTimeZone(value){if(typeof value!=="string"||!value.trim()||value.length>64)return!1;try{new Intl.DateTimeFormat("en-US",{timeZone:value});return!0}catch{return!1}}function dayNumber(ymd,name){if(!isCalendarDate(ymd))throw RangeError(`${name} expects a YYYY-MM-DD calendar date, got "${String(ymd)}"`);return Date.parse(`${ymd}T00:00:00Z`)/DAY_MS}function fromDayNumber(day){const result=new Date(day*DAY_MS).toISOString();if(result.length!==24)throw RangeError("Calendar date out of range");return result.slice(0,10)}export function todayIn(timeZone,now=new Date){if(!isTimeZone(timeZone))throw RangeError(`Unknown time zone "${String(timeZone)}"`);if(!Number.isFinite(now.getTime()))throw RangeError("todayIn expects a valid instant");const parts=new Intl.DateTimeFormat("en-US",{timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(now),get=(type)=>parts.find((part)=>part.type===type)?.value??"";return`${get("year").padStart(4,"0")}-${get("month")}-${get("day")}`}export function addDays(ymd,days){if(!Number.isSafeInteger(days))throw RangeError("addDays expects a whole number of days");return fromDayNumber(dayNumber(ymd,"addDays")+days)}export function daysBetween(from,to){return dayNumber(to,"daysBetween")-dayNumber(from,"daysBetween")}export function startOfIsoWeek(ymd){const day=dayNumber(ymd,"startOfIsoWeek"),weekday=(day%7+7+3)%7;return fromDayNumber(day-weekday)}export function minutesUntil(date,time,timeZone,now=new Date){if(!isCalendarDate(date))throw RangeError(`minutesUntil expects a YYYY-MM-DD date, got "${String(date)}"`);if(typeof time!=="string"||!CLOCK.test(time))throw RangeError(`minutesUntil expects HH:mm or HH:mm:ss, got "${String(time)}"`);if(!isTimeZone(timeZone))throw RangeError(`Unknown time zone "${String(timeZone)}"`);if(!Number.isFinite(now.getTime()))throw RangeError("minutesUntil expects a valid instant");return(zonedTimeToUtc(`${date}T${time}`,timeZone).getTime()-now.getTime())/60000}
1
+ import{zonedFormatter}from"./intl";import{zonedTimeToUtc}from"./zone";export function addCalendarMonths(date,months,options={}){if(!Number.isFinite(date.getTime())||!Number.isSafeInteger(months))throw Error("Calendar arithmetic requires a valid date and integer month count");const result=new Date(date);if(options.utc){const day=result.getUTCDate();result.setUTCDate(1);result.setUTCMonth(result.getUTCMonth()+months);result.setUTCDate(Math.min(day,new Date(Date.UTC(result.getUTCFullYear(),result.getUTCMonth()+1,0)).getUTCDate()))}else{const day=result.getDate();result.setDate(1);result.setMonth(result.getMonth()+months);result.setDate(Math.min(day,new Date(result.getFullYear(),result.getMonth()+1,0).getDate()))}return result}const DAY_MS=86400000,YMD=/^\d{4}-\d{2}-\d{2}$/,CLOCK=/^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/;export function isCalendarDate(value){if(typeof value!=="string"||!YMD.test(value))return!1;const time=Date.parse(`${value}T00:00:00Z`);return Number.isFinite(time)&&new Date(time).toISOString().slice(0,10)===value}export function isTimeZone(value){if(typeof value!=="string"||!value.trim()||value.length>64)return!1;try{zonedFormatter("en-US",{timeZone:value});return!0}catch{return!1}}function dayNumber(ymd,name){if(!isCalendarDate(ymd))throw RangeError(`${name} expects a YYYY-MM-DD calendar date, got "${String(ymd)}"`);return Date.parse(`${ymd}T00:00:00Z`)/DAY_MS}function fromDayNumber(day){const result=new Date(day*DAY_MS).toISOString();if(result.length!==24)throw RangeError("Calendar date out of range");return result.slice(0,10)}export function todayIn(timeZone,now=new Date){if(!isTimeZone(timeZone))throw RangeError(`Unknown time zone "${String(timeZone)}"`);if(!Number.isFinite(now.getTime()))throw RangeError("todayIn expects a valid instant");const parts=zonedFormatter("en-US",{timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(now),get=(type)=>parts.find((part)=>part.type===type)?.value??"";return`${get("year").padStart(4,"0")}-${get("month")}-${get("day")}`}export function addDays(ymd,days){if(!Number.isSafeInteger(days))throw RangeError("addDays expects a whole number of days");return fromDayNumber(dayNumber(ymd,"addDays")+days)}export function daysBetween(from,to){return dayNumber(to,"daysBetween")-dayNumber(from,"daysBetween")}export function startOfIsoWeek(ymd){const day=dayNumber(ymd,"startOfIsoWeek"),weekday=(day%7+7+3)%7;return fromDayNumber(day-weekday)}export function minutesUntil(date,time,timeZone,now=new Date){if(!isCalendarDate(date))throw RangeError(`minutesUntil expects a YYYY-MM-DD date, got "${String(date)}"`);if(typeof time!=="string"||!CLOCK.test(time))throw RangeError(`minutesUntil expects HH:mm or HH:mm:ss, got "${String(time)}"`);if(!isTimeZone(timeZone))throw RangeError(`Unknown time zone "${String(timeZone)}"`);if(!Number.isFinite(now.getTime()))throw RangeError("minutesUntil expects a valid instant");return(zonedTimeToUtc(`${date}T${time}`,timeZone).getTime()-now.getTime())/60000}
package/dist/format.d.ts CHANGED
@@ -35,3 +35,4 @@ declare interface FormatOptions {
35
35
  tz?: string
36
36
  }
37
37
  declare type DateInput = Date | string;
38
+ declare type NameOptions = Pick<Intl.DateTimeFormatOptions, 'month' | 'weekday'>;
package/dist/format.js CHANGED
@@ -1 +1 @@
1
- function toDate(input){if(input instanceof Date)return input;const d=new Date(input);if(Number.isNaN(d.getTime()))throw Error(`Invalid date: ${input}`);return d}function pad(n,len=2){return String(n).padStart(len,"0")}function getPartsInTz(date,tz,locale){const parts=new Intl.DateTimeFormat("en-US",{timeZone:tz,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(date),get=(type)=>parts.find((p)=>p.type===type)?.value??"",year=Number.parseInt(get("year"),10),month=Number.parseInt(get("month"),10),day=Number.parseInt(get("day"),10);let hour=Number.parseInt(get("hour"),10);if(hour===24)hour=0;const minute=Number.parseInt(get("minute"),10),second=Number.parseInt(get("second"),10),weekday=new Intl.DateTimeFormat(locale,{timeZone:tz,weekday:"long"}).format(date),weekdayShort=new Intl.DateTimeFormat(locale,{timeZone:tz,weekday:"short"}).format(date),weekdayNarrow=new Intl.DateTimeFormat(locale,{timeZone:tz,weekday:"narrow"}).format(date),monthLong=new Intl.DateTimeFormat(locale,{timeZone:tz,month:"long"}).format(date),monthShort=new Intl.DateTimeFormat(locale,{timeZone:tz,month:"short"}).format(date),utcParts=new Intl.DateTimeFormat("en-US",{timeZone:"UTC",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(date),getUtc=(type)=>utcParts.find((p)=>p.type===type)?.value??"",utcDate=new Date(Date.UTC(Number.parseInt(getUtc("year"),10),Number.parseInt(getUtc("month"),10)-1,Number.parseInt(getUtc("day"),10),Number.parseInt(getUtc("hour"),10)===24?0:Number.parseInt(getUtc("hour"),10),Number.parseInt(getUtc("minute"),10),Number.parseInt(getUtc("second"),10))),offsetMs=new Date(Date.UTC(year,month-1,day,hour,minute,second)).getTime()-utcDate.getTime(),offsetMin=Math.round(offsetMs/60000),sign=offsetMin>=0?"+":"-",absMin=Math.abs(offsetMin),tzOffset=`${sign}${pad(Math.floor(absMin/60))}${pad(absMin%60)}`;return{year,month,day,hour,minute,second,weekday,weekdayShort,weekdayNarrow,monthLong,monthShort,tzOffset}}function buildTokens(p){const hours12=p.hour%12||12;return{YYYY:String(p.year),YY:String(p.year).slice(-2),MMMM:p.monthLong,MMM:p.monthShort,MM:pad(p.month),M:String(p.month),DD:pad(p.day),D:String(p.day),dddd:p.weekday,ddd:p.weekdayShort,d:p.weekdayNarrow,HH:pad(p.hour),H:String(p.hour),hh:pad(hours12),h:String(hours12),mm:pad(p.minute),m:String(p.minute),ss:pad(p.second),s:String(p.second),A:p.hour<12?"AM":"PM",a:p.hour<12?"am":"pm",Z:p.tzOffset}}const TOKEN_KEYS=["YYYY","MMMM","dddd","MMM","ddd","YY","MM","DD","HH","hh","mm","ss","M","D","d","H","h","m","s","A","a","Z"],TOKEN_PATTERN=new RegExp(TOKEN_KEYS.map((t)=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g");export function format(inputDate,formatStr="YYYY-MM-DD",localeOrOptions="en"){const date=toDate(inputDate),opts=typeof localeOrOptions==="string"?{locale:localeOrOptions}:localeOrOptions,locale=opts.locale??"en",tz=opts.tz;if(tz){const parts=getPartsInTz(date,tz,locale),tokens=buildTokens(parts);return formatStr.replace(TOKEN_PATTERN,(match)=>tokens[match]??match)}const hours24=date.getHours(),hours12=hours24%12||12,tokens={YYYY:String(date.getFullYear()),YY:String(date.getFullYear()).slice(-2),MMMM:new Intl.DateTimeFormat(locale,{month:"long"}).format(date),MMM:new Intl.DateTimeFormat(locale,{month:"short"}).format(date),MM:pad(date.getMonth()+1),M:String(date.getMonth()+1),DD:pad(date.getDate()),D:String(date.getDate()),dddd:new Intl.DateTimeFormat(locale,{weekday:"long"}).format(date),ddd:new Intl.DateTimeFormat(locale,{weekday:"short"}).format(date),d:new Intl.DateTimeFormat(locale,{weekday:"narrow"}).format(date),HH:pad(hours24),H:String(hours24),hh:pad(hours12),h:String(hours12),mm:pad(date.getMinutes()),m:String(date.getMinutes()),ss:pad(date.getSeconds()),s:String(date.getSeconds()),A:hours24<12?"AM":"PM",a:hours24<12?"am":"pm",Z:(()=>{const offset=-date.getTimezoneOffset(),sign=offset>=0?"+":"-",abs=Math.abs(offset);return`${sign}${pad(Math.floor(abs/60))}${pad(abs%60)}`})()};return formatStr.replace(TOKEN_PATTERN,(match)=>tokens[match]??match)}
1
+ import{parse}from"./parse";import{dateFromParts}from"./parts";import{zonedFormatter}from"./intl";function toDate(input){if(input instanceof Date){if(Number.isNaN(input.getTime()))throw Error("Invalid date");return input}const date=new Date(input);if(Number.isNaN(date.getTime()))throw Error(`Invalid date: ${input}`);return/^\d{4}-\d{2}-\d{2}$/.test(input)?parse(input):date}function pad(n,len=2){return String(n).padStart(len,"0")}function getPartsInTz(date,tz){const parts=zonedFormatter("en-US",{timeZone:tz,year:"numeric",era:"short",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(date),get=(type)=>parts.find((p)=>p.type===type)?.value??"",displayedYear=Number.parseInt(get("year"),10),year=get("era")==="BC"?1-displayedYear:displayedYear,month=Number.parseInt(get("month"),10),day=Number.parseInt(get("day"),10);let hour=Number.parseInt(get("hour"),10);if(hour===24)hour=0;const minute=Number.parseInt(get("minute"),10),second=Number.parseInt(get("second"),10);return{year,month,day,hour,minute,second}}function offsetFromParts(date,p){const offsetMs=dateFromParts(p.year,p.month-1,p.day,p.hour,p.minute,p.second,0,!0).getTime()-Math.floor(date.getTime()/1000)*1000;return offsetString(Math.round(offsetMs/60000))}function offsetString(offsetMin){const sign=offsetMin>=0?"+":"-",absMin=Math.abs(offsetMin);return`${sign}${pad(Math.floor(absMin/60))}${pad(absMin%60)}`}function tokenValue(token,p,name,offset){const hours12=p.hour%12||12;switch(token){case"YYYY":return pad(p.year,4);case"YY":return pad(p.year%100);case"MMMM":return name({month:"long"});case"MMM":return name({month:"short"});case"MM":return pad(p.month);case"M":return String(p.month);case"DD":return pad(p.day);case"D":return String(p.day);case"dddd":return name({weekday:"long"});case"ddd":return name({weekday:"short"});case"d":return name({weekday:"narrow"});case"HH":return pad(p.hour);case"H":return String(p.hour);case"hh":return pad(hours12);case"h":return String(hours12);case"mm":return pad(p.minute);case"m":return String(p.minute);case"ss":return pad(p.second);case"s":return String(p.second);case"A":return p.hour<12?"AM":"PM";case"a":return p.hour<12?"am":"pm";case"Z":return offset();default:return token}}const TOKEN_KEYS=["YYYY","MMMM","dddd","MMM","ddd","YY","MM","DD","HH","hh","mm","ss","M","D","d","H","h","m","s","A","a","Z"],TOKEN_PATTERN=new RegExp(TOKEN_KEYS.map((t)=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g");export function format(inputDate,formatStr="YYYY-MM-DD",localeOrOptions="en"){const date=toDate(inputDate),opts=typeof localeOrOptions==="string"?{locale:localeOrOptions}:localeOrOptions,locale=opts.locale??"en",tz=opts.tz;if(tz){const parts=getPartsInTz(date,tz),name=(options)=>zonedFormatter(locale,{timeZone:tz,...options}).format(date);return formatStr.replace(TOKEN_PATTERN,(match)=>tokenValue(match,parts,name,()=>offsetFromParts(date,parts)))}const parts={year:date.getFullYear(),month:date.getMonth()+1,day:date.getDate(),hour:date.getHours(),minute:date.getMinutes(),second:date.getSeconds()},name=(options)=>new Intl.DateTimeFormat(locale,options).format(date);return formatStr.replace(TOKEN_PATTERN,(match)=>tokenValue(match,parts,name,()=>offsetString(-date.getTimezoneOffset())))}
package/dist/intl.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export declare function zonedFormatter(locale: string, options: Intl.DateTimeFormatOptions & { timeZone: string }): Intl.DateTimeFormat;
2
+ /** How many formatters are shared right now (for tests). */
3
+ export declare function sharedFormatterCount(): number;
package/dist/intl.js ADDED
@@ -0,0 +1 @@
1
+ const MAX_FORMATTERS=512,formatters=new Map;export function zonedFormatter(locale,options){const key=`${locale}\x00${JSON.stringify(options)}`,cached=formatters.get(key);if(cached)return cached;const formatter=new Intl.DateTimeFormat(locale,options);if(formatters.size>=MAX_FORMATTERS)formatters.delete(formatters.keys().next().value);formatters.set(key,formatter);return formatter}export function sharedFormatterCount(){return formatters.size}
package/dist/now.js CHANGED
@@ -1 +1 @@
1
- import{format}from"./format";import{parse}from"./parse";export class DateTime{date;constructor(date,formatStr){if(!date)this.date=new Date;else if(date instanceof Date)this.date=new Date(date.getTime());else if(formatStr)this.date=parse(date,formatStr);else this.date=parse(date)}static now(){return new DateTime}static create(year,month=1,day=1,hour=0,minute=0,second=0){return new DateTime(new Date(year,month-1,day,hour,minute,second))}static fromDate(date){return new DateTime(date)}static parse(dateStr,formatStr){return new DateTime(dateStr,formatStr)}format(formatStr,localeOrOptions){return format(this.date,formatStr,localeOrOptions)}toDateString(){return format(this.date,"YYYY-MM-DD")}toTimeString(){return format(this.date,"HH:mm:ss")}toDateTimeString(){return format(this.date,"YYYY-MM-DD HH:mm:ss")}toISOString(){return this.date.toISOString()}toString(){return this.toDateTimeString()}get year(){return this.date.getFullYear()}get month(){return this.date.getMonth()+1}get day(){return this.date.getDate()}get hour(){return this.date.getHours()}get minute(){return this.date.getMinutes()}get second(){return this.date.getSeconds()}get dayOfWeek(){return this.date.getDay()}get timestamp(){return this.date.getTime()}setYear(year){const d=new Date(this.date);d.setFullYear(year);return new DateTime(d)}setMonth(month){const d=new Date(this.date);d.setMonth(month-1);return new DateTime(d)}setDay(day){const d=new Date(this.date);d.setDate(day);return new DateTime(d)}setHour(hour){const d=new Date(this.date);d.setHours(hour);return new DateTime(d)}setMinute(minute){const d=new Date(this.date);d.setMinutes(minute);return new DateTime(d)}setSecond(second){const d=new Date(this.date);d.setSeconds(second);return new DateTime(d)}addSeconds(n){return new DateTime(new Date(this.date.getTime()+n*1000))}addMinutes(n){return new DateTime(new Date(this.date.getTime()+n*60000))}addHours(n){return new DateTime(new Date(this.date.getTime()+n*3600000))}addDays(n){const d=new Date(this.date);d.setDate(d.getDate()+n);return new DateTime(d)}addWeeks(n){return this.addDays(n*7)}addMonths(n){const d=new Date(this.date);d.setMonth(d.getMonth()+n);return new DateTime(d)}addYears(n){const d=new Date(this.date);d.setFullYear(d.getFullYear()+n);return new DateTime(d)}subSeconds(n){return this.addSeconds(-n)}subMinutes(n){return this.addMinutes(-n)}subHours(n){return this.addHours(-n)}subDays(n){return this.addDays(-n)}subWeeks(n){return this.addWeeks(-n)}subMonths(n){return this.addMonths(-n)}subYears(n){return this.addYears(-n)}startOfDay(){const d=new Date(this.date);d.setHours(0,0,0,0);return new DateTime(d)}endOfDay(){const d=new Date(this.date);d.setHours(23,59,59,999);return new DateTime(d)}startOfMonth(){const d=new Date(this.date);d.setDate(1);d.setHours(0,0,0,0);return new DateTime(d)}endOfMonth(){const d=new Date(this.date.getFullYear(),this.date.getMonth()+1,0,23,59,59,999);return new DateTime(d)}startOfYear(){return new DateTime(new Date(this.date.getFullYear(),0,1,0,0,0,0))}endOfYear(){return new DateTime(new Date(this.date.getFullYear(),11,31,23,59,59,999))}isBefore(other){const otherTime=other instanceof DateTime?other.timestamp:other.getTime();return this.date.getTime()<otherTime}isAfter(other){const otherTime=other instanceof DateTime?other.timestamp:other.getTime();return this.date.getTime()>otherTime}isSame(other){const otherTime=other instanceof DateTime?other.timestamp:other.getTime();return this.date.getTime()===otherTime}isSameDay(other){const o=other instanceof Date?other:other.toNativeDate();return this.date.getFullYear()===o.getFullYear()&&this.date.getMonth()===o.getMonth()&&this.date.getDate()===o.getDate()}isBetween(start,end){return this.isAfter(start)&&this.isBefore(end)}isPast(){return this.date.getTime()<Date.now()}isFuture(){return this.date.getTime()>Date.now()}isToday(){return this.isSameDay(new Date)}isLeapYear(){const y=this.date.getFullYear();return y%4===0&&y%100!==0||y%400===0}diffInSeconds(other){const otherTime=other instanceof DateTime?other.timestamp:other.getTime();return Math.floor((this.date.getTime()-otherTime)/1000)}diffInMinutes(other){return Math.floor(this.diffInSeconds(other)/60)}diffInHours(other){return Math.floor(this.diffInSeconds(other)/3600)}diffInDays(other){return Math.floor(this.diffInSeconds(other)/86400)}toNativeDate(){return new Date(this.date.getTime())}toJSON(){return this.toISOString()}valueOf(){return this.date.getTime()}}export function now(){return DateTime.now()}
1
+ import{format}from"./format";import{parse}from"./parse";import{dateFromParts}from"./parts";export class DateTime{date;constructor(date,formatStr){if(date===void 0)this.date=new Date;else if(date instanceof Date){if(!Number.isFinite(date.getTime()))throw RangeError("Invalid date");this.date=new Date(date.getTime())}else if(formatStr)this.date=parse(date,formatStr);else this.date=parse(date)}static now(){return new DateTime}static create(year,month=1,day=1,hour=0,minute=0,second=0){return new DateTime(dateFromParts(year,month-1,day,hour,minute,second))}static fromDate(date){return new DateTime(date)}static parse(dateStr,formatStr){return new DateTime(dateStr,formatStr)}format(formatStr,localeOrOptions){return format(this.date,formatStr,localeOrOptions)}toDateString(){return format(this.date,"YYYY-MM-DD")}toTimeString(){return format(this.date,"HH:mm:ss")}toDateTimeString(){return format(this.date,"YYYY-MM-DD HH:mm:ss")}toISOString(){return this.date.toISOString()}toString(){return this.toDateTimeString()}get year(){return this.date.getFullYear()}get month(){return this.date.getMonth()+1}get day(){return this.date.getDate()}get hour(){return this.date.getHours()}get minute(){return this.date.getMinutes()}get second(){return this.date.getSeconds()}get dayOfWeek(){return this.date.getDay()}get timestamp(){return this.date.getTime()}setYear(year){const d=new Date(this.date);d.setFullYear(year);return new DateTime(d)}setMonth(month){const d=new Date(this.date);d.setMonth(month-1);return new DateTime(d)}setDay(day){const d=new Date(this.date);d.setDate(day);return new DateTime(d)}setHour(hour){const d=new Date(this.date);d.setHours(hour);return new DateTime(d)}setMinute(minute){const d=new Date(this.date);d.setMinutes(minute);return new DateTime(d)}setSecond(second){const d=new Date(this.date);d.setSeconds(second);return new DateTime(d)}addSeconds(n){return new DateTime(new Date(this.date.getTime()+n*1000))}addMinutes(n){return new DateTime(new Date(this.date.getTime()+n*60000))}addHours(n){return new DateTime(new Date(this.date.getTime()+n*3600000))}addDays(n){const d=new Date(this.date);d.setDate(d.getDate()+n);return new DateTime(d)}addWeeks(n){return this.addDays(n*7)}addMonths(n){const d=new Date(this.date);d.setMonth(d.getMonth()+n);return new DateTime(d)}addYears(n){const d=new Date(this.date);d.setFullYear(d.getFullYear()+n);return new DateTime(d)}subSeconds(n){return this.addSeconds(-n)}subMinutes(n){return this.addMinutes(-n)}subHours(n){return this.addHours(-n)}subDays(n){return this.addDays(-n)}subWeeks(n){return this.addWeeks(-n)}subMonths(n){return this.addMonths(-n)}subYears(n){return this.addYears(-n)}startOfDay(){const d=new Date(this.date);d.setHours(0,0,0,0);return new DateTime(d)}endOfDay(){const d=new Date(this.date);d.setHours(23,59,59,999);return new DateTime(d)}startOfMonth(){const d=new Date(this.date);d.setDate(1);d.setHours(0,0,0,0);return new DateTime(d)}endOfMonth(){const d=dateFromParts(this.date.getFullYear(),this.date.getMonth()+1,0,23,59,59,999);return new DateTime(d)}startOfYear(){return new DateTime(dateFromParts(this.date.getFullYear(),0,1))}endOfYear(){return new DateTime(dateFromParts(this.date.getFullYear(),11,31,23,59,59,999))}isBefore(other){const otherTime=other instanceof DateTime?other.timestamp:other.getTime();return this.date.getTime()<otherTime}isAfter(other){const otherTime=other instanceof DateTime?other.timestamp:other.getTime();return this.date.getTime()>otherTime}isSame(other){const otherTime=other instanceof DateTime?other.timestamp:other.getTime();return this.date.getTime()===otherTime}isSameDay(other){const o=other instanceof Date?other:other.toNativeDate();return this.date.getFullYear()===o.getFullYear()&&this.date.getMonth()===o.getMonth()&&this.date.getDate()===o.getDate()}isBetween(start,end){return this.isAfter(start)&&this.isBefore(end)}isPast(){return this.date.getTime()<Date.now()}isFuture(){return this.date.getTime()>Date.now()}isToday(){return this.isSameDay(new Date)}isLeapYear(){const y=this.date.getFullYear();return y%4===0&&y%100!==0||y%400===0}diffInSeconds(other){const otherTime=other instanceof DateTime?other.timestamp:other.getTime();return Math.floor((this.date.getTime()-otherTime)/1000)}diffInMinutes(other){return Math.floor(this.diffInSeconds(other)/60)}diffInHours(other){return Math.floor(this.diffInSeconds(other)/3600)}diffInDays(other){return Math.floor(this.diffInSeconds(other)/86400)}toNativeDate(){return new Date(this.date.getTime())}toJSON(){return this.toISOString()}valueOf(){return this.date.getTime()}}export function now(){return DateTime.now()}
package/dist/parse.d.ts CHANGED
@@ -10,4 +10,4 @@
10
10
  * When no format is given, falls back to native Date parsing (with a fix
11
11
  * for date-only ISO strings being treated as local time, not UTC).
12
12
  */
13
- export declare function parse(dateStr: string, formatStr?: string, _locale?: string): Date;
13
+ export declare function parse(dateStr: string, formatStr?: string, locale?: string): Date;
package/dist/parse.js CHANGED
@@ -1 +1 @@
1
- export function parse(dateStr,formatStr,_locale){if(!formatStr){if(/^\d{4}-\d{2}-\d{2}$/.test(dateStr)){const[y,m,d]=dateStr.split("-").map(Number);if(y===void 0||m===void 0||d===void 0)throw Error(`Unable to parse date: ${dateStr}`);return new Date(y,m-1,d)}const d=new Date(dateStr);if(Number.isNaN(d.getTime()))throw Error(`Unable to parse date: ${dateStr}`);return d}const tokenDefs={YYYY:{regex:"(\\d{4})",field:"year"},YY:{regex:"(\\d{2})",field:"shortYear"},MMMM:{regex:"(\\w+)",field:"monthName"},MMM:{regex:"(\\w+)",field:"monthNameShort"},MM:{regex:"(\\d{2})",field:"month"},M:{regex:"(\\d{1,2})",field:"month"},DD:{regex:"(\\d{2})",field:"day"},D:{regex:"(\\d{1,2})",field:"day"},HH:{regex:"(\\d{2})",field:"hours"},H:{regex:"(\\d{1,2})",field:"hours"},hh:{regex:"(\\d{2})",field:"hours12"},h:{regex:"(\\d{1,2})",field:"hours12"},mm:{regex:"(\\d{2})",field:"minutes"},m:{regex:"(\\d{1,2})",field:"minutes"},ss:{regex:"(\\d{2})",field:"seconds"},s:{regex:"(\\d{1,2})",field:"seconds"},A:{regex:"(AM|PM)",field:"ampm"},a:{regex:"(am|pm)",field:"ampm"},Z:{regex:"([+-]\\d{4})",field:"tz"}},sortedTokens=Object.keys(tokenDefs).sort((a,b)=>b.length-a.length),tokenRegex=new RegExp(sortedTokens.map((t)=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g"),fields=[],regexStr=formatStr.replace(tokenRegex,(match)=>{const def=tokenDefs[match];if(def){fields.push(def.field);return def.regex}return match}),result=new RegExp(`^${regexStr}$`).exec(dateStr);if(!result)throw Error(`Unable to parse "${dateStr}" with format "${formatStr}"`);const parts={};for(let i=0;i<fields.length;i++){const field=fields[i],value=result[i+1];if(field!==void 0&&value!==void 0)parts[field]=value}let month=0;if(parts.month)month=Number.parseInt(parts.month,10)-1;else if(parts.monthName||parts.monthNameShort){const name=(parts.monthName||parts.monthNameShort||"").toLowerCase(),months=["january","february","march","april","may","june","july","august","september","october","november","december"],shortMonths=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];let idx=months.indexOf(name);if(idx===-1)idx=shortMonths.indexOf(name);if(idx===-1)throw Error(`Unknown month: ${parts.monthName||parts.monthNameShort}`);month=idx}let year=parts.year?Number.parseInt(parts.year,10):new Date().getFullYear();if(parts.shortYear){const shortYear=Number.parseInt(parts.shortYear,10);year=shortYear>=70?1900+shortYear:2000+shortYear}let hours=Number.parseInt(parts.hours||parts.hours12||"0",10);if(parts.ampm){const isPM=parts.ampm.toLowerCase()==="pm";if(isPM&&hours<12)hours+=12;if(!isPM&&hours===12)hours=0}const day=Number.parseInt(parts.day||"1",10),minutes=Number.parseInt(parts.minutes||"0",10),seconds=Number.parseInt(parts.seconds||"0",10);if(parts.tz){const sign=parts.tz[0]==="+"?1:-1,tzHours=Number.parseInt(parts.tz.slice(1,3),10),tzMinutes=Number.parseInt(parts.tz.slice(3,5),10),offsetMs=sign*(tzHours*60+tzMinutes)*60000,utcMs=Date.UTC(year,month,day,hours,minutes,seconds)-offsetMs;return new Date(utcMs)}return new Date(year,month,day,hours,minutes,seconds)}
1
+ import{zonedFormatter}from"./intl";import{dateFromParts}from"./parts";function validateCalendar(year,month,day){const date=dateFromParts(year,month,day,0,0,0,0,!0);if(date.getUTCFullYear()!==year||date.getUTCMonth()!==month||date.getUTCDate()!==day)throw RangeError("Invalid calendar date")}export function parse(dateStr,formatStr,locale="en"){if(!formatStr){if(/^\d{4}-\d{2}-\d{2}$/.test(dateStr)){const[y,m,d]=dateStr.split("-").map(Number);if(y===void 0||m===void 0||d===void 0)throw Error(`Unable to parse date: ${dateStr}`);validateCalendar(y,m-1,d);return dateFromParts(y,m-1,d)}const d=new Date(dateStr);if(Number.isNaN(d.getTime()))throw Error(`Unable to parse date: ${dateStr}`);return d}const tokenDefs={YYYY:{regex:"(\\d{4})",field:"year"},YY:{regex:"(\\d{2})",field:"shortYear"},MMMM:{regex:"(.+?)",field:"monthName"},MMM:{regex:"(.+?)",field:"monthNameShort"},MM:{regex:"(\\d{2})",field:"month"},M:{regex:"(\\d{1,2})",field:"month"},DD:{regex:"(\\d{2})",field:"day"},D:{regex:"(\\d{1,2})",field:"day"},HH:{regex:"(\\d{2})",field:"hours"},H:{regex:"(\\d{1,2})",field:"hours"},hh:{regex:"(\\d{2})",field:"hours12"},h:{regex:"(\\d{1,2})",field:"hours12"},mm:{regex:"(\\d{2})",field:"minutes"},m:{regex:"(\\d{1,2})",field:"minutes"},ss:{regex:"(\\d{2})",field:"seconds"},s:{regex:"(\\d{1,2})",field:"seconds"},A:{regex:"(AM|PM)",field:"ampm"},a:{regex:"(am|pm)",field:"ampm"},Z:{regex:"([+-]\\d{4})",field:"tz"}},sortedTokens=Object.keys(tokenDefs).sort((a,b)=>b.length-a.length),tokenRegex=new RegExp(sortedTokens.map((t)=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g"),fields=[],escape=(literal)=>literal.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");let regexStr="",cursor=0;for(const match of formatStr.matchAll(tokenRegex)){regexStr+=escape(formatStr.slice(cursor,match.index));const token=match[0],def=tokenDefs[token];fields.push(def.field);regexStr+=def.regex;cursor=match.index+token.length}regexStr+=escape(formatStr.slice(cursor));const result=new RegExp(`^${regexStr}$`).exec(dateStr);if(!result)throw Error(`Unable to parse "${dateStr}" with format "${formatStr}"`);const parts={};for(let i=0;i<fields.length;i++){const field=fields[i],value=result[i+1];if(field!==void 0&&value!==void 0)parts[field]=value}let month=0;if(parts.month)month=Number.parseInt(parts.month,10)-1;else if(parts.monthName||parts.monthNameShort){const normalize=(name)=>name.normalize("NFC").toLocaleLowerCase(locale),name=normalize(parts.monthName||parts.monthNameShort||""),long=zonedFormatter(locale,{month:"long",timeZone:"UTC"}),short=zonedFormatter(locale,{month:"short",timeZone:"UTC"}),idx=Array.from({length:12},(_,index)=>index).find((index)=>{const date=dateFromParts(2024,index,15,12,0,0,0,!0);return normalize(long.format(date))===name||normalize(short.format(date))===name});if(idx===void 0)throw Error(`Unknown month: ${parts.monthName||parts.monthNameShort}`);month=idx}let year=parts.year?Number.parseInt(parts.year,10):new Date().getFullYear();if(parts.shortYear){const shortYear=Number.parseInt(parts.shortYear,10);year=shortYear>=70?1900+shortYear:2000+shortYear}let hours=Number.parseInt(parts.hours||parts.hours12||"0",10);if(hours<(parts.hours12?1:0)||hours>(parts.hours12?12:23))throw RangeError("Invalid clock hour");if(parts.ampm){const isPM=parts.ampm.toLowerCase()==="pm";if(isPM&&hours<12)hours+=12;if(!isPM&&hours===12)hours=0}const day=Number.parseInt(parts.day||"1",10),minutes=Number.parseInt(parts.minutes||"0",10),seconds=Number.parseInt(parts.seconds||"0",10);validateCalendar(year,month,day);if(minutes>59||seconds>59)throw RangeError("Invalid clock time");if(parts.tz){const sign=parts.tz[0]==="+"?1:-1,tzHours=Number.parseInt(parts.tz.slice(1,3),10),tzMinutes=Number.parseInt(parts.tz.slice(3,5),10);if(tzHours>23||tzMinutes>59)throw RangeError("Invalid timezone offset");const offsetMs=sign*(tzHours*60+tzMinutes)*60000,utcMs=dateFromParts(year,month,day,hours,minutes,seconds,0,!0).getTime()-offsetMs;return new Date(utcMs)}return dateFromParts(year,month,day,hours,minutes,seconds)}
@@ -0,0 +1,2 @@
1
+ /** Numeric Date constructors remap 0..99 to 1900..1999. Set the full year explicitly. */
2
+ export declare function dateFromParts(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, millisecond?: number, utc?: boolean): Date;
package/dist/parts.js ADDED
@@ -0,0 +1 @@
1
+ export function dateFromParts(year,month,day,hour=0,minute=0,second=0,millisecond=0,utc=!1){const date=new Date(0);if(utc){date.setUTCFullYear(year,month,day);date.setUTCHours(hour,minute,second,millisecond)}else{date.setFullYear(year,month,day);date.setHours(hour,minute,second,millisecond)}return date}
package/dist/zone.js CHANGED
@@ -1 +1 @@
1
- const DAY_MS=86400000,WALL_CLOCK=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?$/;export function zoneOffsetMinutes(instant,timeZone){const parts=new Intl.DateTimeFormat("en-US",{timeZone,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(instant),get=(type)=>Number(parts.find((p)=>p.type===type)?.value??0),reading=new Date(Date.UTC(2000,get("month")-1,get("day"),get("hour"),get("minute"),get("second")));reading.setUTCFullYear(get("year"));const asUtc=reading.getTime(),whole=Math.floor(instant.getTime()/1000)*1000;return Math.round((asUtc-whole)/60000)}export function zonedTimeToUtc(wallClock,timeZone){const match=WALL_CLOCK.exec(wallClock.trim());if(!match)throw TypeError(`zonedTimeToUtc expects a wall-clock time like 2026-10-01T20:00:00, got "${wallClock}"`);const[,y,mo,d,h="0",mi="0",s="0"]=match,reading=new Date(Date.UTC(2000,Number(mo)-1,Number(d),Number(h),Number(mi),Number(s)));reading.setUTCFullYear(Number(y));const local=reading.getTime(),before=zoneOffsetMinutes(new Date(local-DAY_MS),timeZone),after=zoneOffsetMinutes(new Date(local+DAY_MS),timeZone),shows=(offset)=>{const instant=local-offset*60000;return zoneOffsetMinutes(new Date(instant),timeZone)===offset?instant:null},valid=[shows(before),shows(after)].filter((instant)=>instant!==null);if(valid.length)return new Date(Math.min(...valid));return new Date(local-before*60000)}export function isoInZone(instant,timeZone){const offset=zoneOffsetMinutes(instant,timeZone),local=new Date(Math.floor(instant.getTime()/1000)*1000+offset*60000),sign=offset<0?"-":"+",abs=Math.abs(offset),pad=(n)=>String(n).padStart(2,"0");return`${local.toISOString().slice(0,19)}${sign}${pad(Math.floor(abs/60))}:${pad(abs%60)}`}
1
+ import{zonedFormatter}from"./intl";const DAY_MS=86400000,WALL_CLOCK=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?$/;export function zoneOffsetMinutes(instant,timeZone){const parts=zonedFormatter("en-US",{timeZone,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(instant),get=(type)=>Number(parts.find((p)=>p.type===type)?.value??0),reading=new Date(Date.UTC(2000,get("month")-1,get("day"),get("hour"),get("minute"),get("second")));reading.setUTCFullYear(get("year"));const asUtc=reading.getTime(),whole=Math.floor(instant.getTime()/1000)*1000;return Math.round((asUtc-whole)/60000)}export function zonedTimeToUtc(wallClock,timeZone){const match=WALL_CLOCK.exec(wallClock.trim());if(!match)throw TypeError(`zonedTimeToUtc expects a wall-clock time like 2026-10-01T20:00:00, got "${wallClock}"`);const[,y,mo,d,h="0",mi="0",s="0"]=match,reading=new Date(Date.UTC(2000,Number(mo)-1,Number(d),Number(h),Number(mi),Number(s)));reading.setUTCFullYear(Number(y));const local=reading.getTime(),before=zoneOffsetMinutes(new Date(local-DAY_MS),timeZone),after=zoneOffsetMinutes(new Date(local+DAY_MS),timeZone),shows=(offset)=>{const instant=local-offset*60000;return zoneOffsetMinutes(new Date(instant),timeZone)===offset?instant:null},valid=[shows(before),shows(after)].filter((instant)=>instant!==null);if(valid.length)return new Date(Math.min(...valid));return new Date(local-before*60000)}export function isoInZone(instant,timeZone){const offset=zoneOffsetMinutes(instant,timeZone),local=new Date(Math.floor(instant.getTime()/1000)*1000+offset*60000),sign=offset<0?"-":"+",abs=Math.abs(offset),pad=(n)=>String(n).padStart(2,"0");return`${local.toISOString().slice(0,19)}${sign}${pad(Math.floor(abs/60))}:${pad(abs%60)}`}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@stacksjs/datetime",
3
3
  "type": "module",
4
- "version": "0.75.423",
4
+ "version": "0.75.431",
5
5
  "description": "The Stacks datetime helpers.",
6
6
  "author": "Chris Breuer",
7
7
  "contributors": [
@@ -59,7 +59,7 @@
59
59
  },
60
60
  "devDependencies": {
61
61
  "better-dx": "^0.2.24",
62
- "@stacksjs/utils": "0.75.423"
62
+ "@stacksjs/utils": "0.75.431"
63
63
  },
64
64
  "sideEffects": false
65
65
  }