@stacksjs/datetime 0.75.515 → 0.75.518

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/dist/calendar.js CHANGED
@@ -1 +1 @@
1
- import{zonedFormatter}from"./intl";import{zonedTimeToUtc}from"./zone";export function addCalendarMonths(date,months,options={}){if(!Number.isFinite(date.getTime())||!Number.isSafeInteger(months))throw RangeError("Calendar arithmetic requires a valid date and integer month count");if(months===0)return new Date(date);const utc=options.utc===!0,year=utc?date.getUTCFullYear():date.getFullYear(),month=utc?date.getUTCMonth():date.getMonth(),total=year*12+month+months;if(!Number.isSafeInteger(total))throw RangeError("Calendar month result out of range");const targetYear=Math.floor(total/12),targetMonth=(total%12+12)%12,leap=targetYear%4===0&&(targetYear%100!==0||targetYear%400===0),days=targetMonth===1?leap?29:28:[31,28,31,30,31,30,31,31,30,31,30,31][targetMonth],result=new Date(date),day=Math.min(utc?date.getUTCDate():date.getDate(),days);if(utc)result.setUTCFullYear(targetYear,targetMonth,day);else result.setFullYear(targetYear,targetMonth,day);if(!Number.isFinite(result.getTime()))throw RangeError("Calendar month result out of range");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",era:"short",month:"2-digit",day:"2-digit"}).formatToParts(now),get=(type)=>parts.find((part)=>part.type===type)?.value??"",year=get("era")==="BC"?1-Number(get("year")):Number(get("year"));if(year<0||year>9999)throw RangeError("Calendar date out of range");return`${String(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 new RangeError("Calendar arithmetic requires a valid date and integer month count");if(months===0)return new Date(date);const utc=options.utc===true;const year=utc?date.getUTCFullYear():date.getFullYear();const month=utc?date.getUTCMonth():date.getMonth();const total=year*12+month+months;if(!Number.isSafeInteger(total))throw new RangeError("Calendar month result out of range");const targetYear=Math.floor(total/12);const targetMonth=(total%12+12)%12;const leap=targetYear%4===0&&(targetYear%100!==0||targetYear%400===0);const days=targetMonth===1?leap?29:28:[31,28,31,30,31,30,31,31,30,31,30,31][targetMonth];const result=new Date(date);const day=Math.min(utc?date.getUTCDate():date.getDate(),days);if(utc)result.setUTCFullYear(targetYear,targetMonth,day);else result.setFullYear(targetYear,targetMonth,day);if(!Number.isFinite(result.getTime()))throw new RangeError("Calendar month result out of range");return result}const DAY_MS=86400000;const YMD=/^\d{4}-\d{2}-\d{2}$/;const CLOCK=/^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/;export function isCalendarDate(value){if(typeof value!=="string"||!YMD.test(value))return false;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 false;try{zonedFormatter("en-US",{timeZone:value});return true}catch{return false}}function dayNumber(ymd,name){if(!isCalendarDate(ymd))throw new 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 new RangeError("Calendar date out of range");return result.slice(0,10)}export function todayIn(timeZone,now=new Date){if(!isTimeZone(timeZone))throw new RangeError(`Unknown time zone "${String(timeZone)}"`);if(!Number.isFinite(now.getTime()))throw new RangeError("todayIn expects a valid instant");const parts=zonedFormatter("en-US",{timeZone,year:"numeric",era:"short",month:"2-digit",day:"2-digit"}).formatToParts(now);const get=(type)=>parts.find((part)=>part.type===type)?.value??"";const year=get("era")==="BC"?1-Number(get("year")):Number(get("year"));if(year<0||year>9999)throw new RangeError("Calendar date out of range");return`${String(year).padStart(4,"0")}-${get("month")}-${get("day")}`}export function addDays(ymd,days){if(!Number.isSafeInteger(days))throw new 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");const weekday=(day%7+7+3)%7;return fromDayNumber(day-weekday)}export function minutesUntil(date,time,timeZone,now=new Date){if(!isCalendarDate(date))throw new RangeError(`minutesUntil expects a YYYY-MM-DD date, got "${String(date)}"`);if(typeof time!=="string"||!CLOCK.test(time))throw new RangeError(`minutesUntil expects HH:mm or HH:mm:ss, got "${String(time)}"`);if(!isTimeZone(timeZone))throw new RangeError(`Unknown time zone "${String(timeZone)}"`);if(!Number.isFinite(now.getTime()))throw new RangeError("minutesUntil expects a valid instant");return(zonedTimeToUtc(`${date}T${time}`,timeZone).getTime()-now.getTime())/60000}
package/dist/format.js CHANGED
@@ -1 +1 @@
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())))}
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 new Error("Invalid date");return input}const date=new Date(input);if(Number.isNaN(date.getTime()))throw new 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:false}).formatToParts(date);const get=(type)=>parts.find((p)=>p.type===type)?.value??"";const displayedYear=Number.parseInt(get("year"),10);const year=get("era")==="BC"?1-displayedYear:displayedYear;const month=Number.parseInt(get("month"),10);const 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);const second=Number.parseInt(get("second"),10);return{year,month,day,hour,minute,second}}function offsetFromParts(date,p){const wallClock=dateFromParts(p.year,p.month-1,p.day,p.hour,p.minute,p.second,0,true);const offsetMs=wallClock.getTime()-Math.floor(date.getTime()/1000)*1000;return offsetString(Math.round(offsetMs/60000))}function offsetString(offsetMin){const sign=offsetMin>=0?"+":"-";const 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"];const 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);const opts=typeof localeOrOptions==="string"?{locale:localeOrOptions}:localeOrOptions;const locale=opts.locale??"en";const tz=opts.tz;if(tz){const parts=getPartsInTz(date,tz);const 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()};const 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.js CHANGED
@@ -1 +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}
1
+ const MAX_FORMATTERS=512;const formatters=new Map;export function zonedFormatter(locale,options){const key=`${locale}\x00${JSON.stringify(options)}`;const 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/local.js CHANGED
@@ -1 +1 @@
1
- import{format}from"./format";export function localDateTime(instant,...timeZones){if(!Number.isFinite(instant.getTime()))throw RangeError("Invalid clock instant");for(const zone of[...timeZones,"UTC"]){if(typeof zone!=="string"||!zone.trim())continue;try{const timeZone=zone.trim(),clock=format(instant,"YYYY-MM-DD HH:mm",{tz:timeZone});return{date:clock.slice(0,10),time:clock.slice(11),timeZone}}catch(error){if(!(error instanceof RangeError))throw error}}throw RangeError("Cannot resolve a local clock")}
1
+ import{format}from"./format";export function localDateTime(instant,...timeZones){if(!Number.isFinite(instant.getTime()))throw new RangeError("Invalid clock instant");for(const zone of[...timeZones,"UTC"]){if(typeof zone!=="string"||!zone.trim())continue;try{const timeZone=zone.trim();const clock=format(instant,"YYYY-MM-DD HH:mm",{tz:timeZone});return{date:clock.slice(0,10),time:clock.slice(11),timeZone}}catch(error){if(!(error instanceof RangeError))throw error}}throw new RangeError("Cannot resolve a local clock")}
package/dist/now.js CHANGED
@@ -1 +1 @@
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()}
1
+ import{format}from"./format";import{parse}from"./parse";import{dateFromParts}from"./parts";export class DateTime{date;constructor(date,formatStr){if(date===undefined){this.date=new Date}else if(date instanceof Date){if(!Number.isFinite(date.getTime()))throw new 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.js CHANGED
@@ -1 +1 @@
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)}
1
+ import{zonedFormatter}from"./intl";import{dateFromParts}from"./parts";function validateCalendar(year,month,day){const date=dateFromParts(year,month,day,0,0,0,0,true);if(date.getUTCFullYear()!==year||date.getUTCMonth()!==month||date.getUTCDate()!==day)throw new 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===undefined||m===undefined||d===undefined){throw new 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 new 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"}};const sortedTokens=Object.keys(tokenDefs).sort((a,b)=>b.length-a.length);const tokenRegex=new RegExp(sortedTokens.map((t)=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g");const fields=[];const escape=(literal)=>literal.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");let regexStr="";let cursor=0;for(const match of formatStr.matchAll(tokenRegex)){regexStr+=escape(formatStr.slice(cursor,match.index));const token=match[0];const def=tokenDefs[token];fields.push(def.field);regexStr+=def.regex;cursor=match.index+token.length}regexStr+=escape(formatStr.slice(cursor));const finalRegex=new RegExp(`^${regexStr}$`);const result=finalRegex.exec(dateStr);if(!result){throw new Error(`Unable to parse "${dateStr}" with format "${formatStr}"`)}const parts={};for(let i=0;i<fields.length;i++){const field=fields[i];const value=result[i+1];if(field!==undefined&&value!==undefined)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);const name=normalize(parts.monthName||parts.monthNameShort||"");const long=zonedFormatter(locale,{month:"long",timeZone:"UTC"});const short=zonedFormatter(locale,{month:"short",timeZone:"UTC"});const idx=Array.from({length:12},(_,index)=>index).find((index)=>{const date=dateFromParts(2024,index,15,12,0,0,0,true);return normalize(long.format(date))===name||normalize(short.format(date))===name});if(idx===undefined)throw new 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 new 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);const minutes=Number.parseInt(parts.minutes||"0",10);const seconds=Number.parseInt(parts.seconds||"0",10);validateCalendar(year,month,day);if(minutes>59||seconds>59)throw new RangeError("Invalid clock time");if(parts.tz){const sign=parts.tz[0]==="+"?1:-1;const tzHours=Number.parseInt(parts.tz.slice(1,3),10);const tzMinutes=Number.parseInt(parts.tz.slice(3,5),10);if(tzHours>23||tzMinutes>59)throw new RangeError("Invalid timezone offset");const offsetMs=sign*(tzHours*60+tzMinutes)*60000;const utcMs=dateFromParts(year,month,day,hours,minutes,seconds,0,true).getTime()-offsetMs;return new Date(utcMs)}return dateFromParts(year,month,day,hours,minutes,seconds)}
package/dist/parts.js CHANGED
@@ -1 +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}
1
+ export function dateFromParts(year,month,day,hour=0,minute=0,second=0,millisecond=0,utc=false){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/schedule.js CHANGED
@@ -1 +1 @@
1
- import{localDateTime}from"./local";import{zonedTimeToUtc}from"./zone";export class ScheduleInputError extends RangeError{status=422}const DAY=86400000;export function calendarDay(value){if(typeof value!=="string"||!/^\d{4}-\d{2}-\d{2}$/.test(value))throw new ScheduleInputError("Use yyyy-mm-dd dates");const date=new Date(`${value}T00:00:00Z`);if(!Number.isFinite(date.getTime())||date.toISOString().slice(0,10)!==value)throw new ScheduleInputError("Invalid calendar date");return date.getTime()/DAY}export function clockMinutes(value){if(typeof value!=="string"||!/^\d{2}:\d{2}$/.test(value))throw new ScheduleInputError("Use HH:MM times");const[hour,minute]=value.split(":").map(Number);if(hour>23||minute>59)throw new ScheduleInputError("Invalid clock time");return hour*60+minute}export function addClockMinutes(start,duration){if(!Number.isSafeInteger(duration)||duration<=0)throw new ScheduleInputError("Duration must be positive whole minutes");const end=clockMinutes(start)+duration;if(end>=1440)throw new ScheduleInputError("Session must end before midnight; shorten it or move its start time");return`${String(Math.floor(end/60)).padStart(2,"0")}:${String(end%60).padStart(2,"0")}`}export function parseWeeklySchedule(value){try{const data=typeof value==="string"?JSON.parse(value):value;if(!data||typeof data!=="object"||Array.isArray(data)||!Array.isArray(data.weekdays)||!data.weekdays.length)return null;const weekdays=data.weekdays.map((day)=>{if(typeof day!=="number"&&(typeof day!=="string"||!/^[0-6]$/.test(day.trim())))throw new ScheduleInputError("Invalid weekday");const number=Number(day);if(!Number.isInteger(number)||number<0||number>6)throw new ScheduleInputError("Invalid weekday");return number});clockMinutes(data.start_time);return{weekdays:[...new Set(weekdays)],start_time:data.start_time}}catch(error){if(error instanceof SyntaxError||error instanceof ScheduleInputError)return null;throw error}}export function expandWeeklySchedule(spec,from,to,duration,maxDays=800){const first=calendarDay(from),last=calendarDay(to);if(!Number.isSafeInteger(maxDays)||maxDays<1)throw new ScheduleInputError("Invalid date-range limit");if(last<first)throw new ScheduleInputError("from must be on or before to");if(last-first+1>maxDays)throw new ScheduleInputError(`Generate at most ${maxDays} days at a time`);const schedule=parseWeeklySchedule(spec);if(!schedule)throw new ScheduleInputError("Invalid recurrence");const end=addClockMinutes(schedule.start_time,duration),days=new Set(schedule.weekdays),slots=[];for(let day=first;day<=last;day++){const date=new Date(day*DAY);if(days.has(date.getUTCDay()))slots.push({session_date:date.toISOString().slice(0,10),start_time:schedule.start_time,end_time:end})}return slots}export function timeWindowsCover(windows,start,end){const first=clockMinutes(start),last=clockMinutes(end),spans=windows.map((window)=>{const span={start:clockMinutes(window.start_time),end:clockMinutes(window.end_time)};if(span.end<=span.start)throw new ScheduleInputError("Availability must end after it starts");return span}).sort((a,b)=>a.start-b.start);if(first>=last)return!1;let covered=first;for(const span of spans){if(span.start>covered)break;covered=Math.max(covered,span.end);if(covered>=last)return!0}return!1}export function localDateRange(from,to,...zones){const first=calendarDay(from),last=calendarDay(to);if(last<first)throw new ScheduleInputError("from must be on or before to");if(Number(from.slice(0,4))<101||to>="9999-12-31")throw new ScheduleInputError("Local ranges support dates from 0101-01-01 through 9999-12-30");const timeZone=localDateTime(new Date(first*DAY),...zones).timeZone,next=new Date((last+1)*DAY).toISOString().slice(0,10);return{start:zonedTimeToUtc(`${from}T00:00:00`,timeZone),end:zonedTimeToUtc(`${next}T00:00:00`,timeZone),timeZone}}export function netHoursBetween(start,end,breakMinutes=0){if(start==null||end==null||!Number.isFinite(breakMinutes))return 0;const first=start instanceof Date?start.getTime():Date.parse(start),last=end instanceof Date?end.getTime():Date.parse(end);if(!Number.isFinite(first)||!Number.isFinite(last)||last<=first)return 0;return Math.max(0,(last-first)/3600000-Math.max(0,breakMinutes)/60)}export function localTimeSpan(date,start,end,...zones){const day=calendarDay(date),first=clockMinutes(start),last=clockMinutes(end);if(first===last)throw new ScheduleInputError("An interval must have distinct start and end times");if(Number(date.slice(0,4))<101||date>="9999-12-31")throw new ScheduleInputError("Unsupported local interval date");const timeZone=localDateTime(new Date(day*DAY),...zones).timeZone,endDate=last<first?new Date((day+1)*DAY).toISOString().slice(0,10):date,interval={start:zonedTimeToUtc(`${date}T${start}:00`,timeZone),end:zonedTimeToUtc(`${endDate}T${end}:00`,timeZone),timeZone};if(interval.end<=interval.start)throw new ScheduleInputError("The local interval has no positive duration in this timezone");return interval}export function timeSpansOverlap(first,second){for(const span of[first,second])if(!Number.isFinite(span.start.getTime())||!Number.isFinite(span.end.getTime())||span.end<=span.start)throw new ScheduleInputError("An interval must contain a positive elapsed duration");return first.start<second.end&&first.end>second.start}
1
+ import{localDateTime}from"./local";import{zonedTimeToUtc}from"./zone";export class ScheduleInputError extends RangeError{status=422}const DAY=86400000;export function calendarDay(value){if(typeof value!=="string"||!/^\d{4}-\d{2}-\d{2}$/.test(value))throw new ScheduleInputError("Use yyyy-mm-dd dates");const date=new Date(`${value}T00:00:00Z`);if(!Number.isFinite(date.getTime())||date.toISOString().slice(0,10)!==value)throw new ScheduleInputError("Invalid calendar date");return date.getTime()/DAY}export function clockMinutes(value){if(typeof value!=="string"||!/^\d{2}:\d{2}$/.test(value))throw new ScheduleInputError("Use HH:MM times");const[hour,minute]=value.split(":").map(Number);if(hour>23||minute>59)throw new ScheduleInputError("Invalid clock time");return hour*60+minute}export function addClockMinutes(start,duration){if(!Number.isSafeInteger(duration)||duration<=0)throw new ScheduleInputError("Duration must be positive whole minutes");const end=clockMinutes(start)+duration;if(end>=1440)throw new ScheduleInputError("Session must end before midnight; shorten it or move its start time");return`${String(Math.floor(end/60)).padStart(2,"0")}:${String(end%60).padStart(2,"0")}`}export function parseWeeklySchedule(value){try{const data=typeof value==="string"?JSON.parse(value):value;if(!data||typeof data!=="object"||Array.isArray(data)||!Array.isArray(data.weekdays)||!data.weekdays.length)return null;const weekdays=data.weekdays.map((day)=>{if(typeof day!=="number"&&(typeof day!=="string"||!/^[0-6]$/.test(day.trim())))throw new ScheduleInputError("Invalid weekday");const number=Number(day);if(!Number.isInteger(number)||number<0||number>6)throw new ScheduleInputError("Invalid weekday");return number});clockMinutes(data.start_time);return{weekdays:[...new Set(weekdays)],start_time:data.start_time}}catch(error){if(error instanceof SyntaxError||error instanceof ScheduleInputError)return null;throw error}}export function expandWeeklySchedule(spec,from,to,duration,maxDays=800){const first=calendarDay(from);const last=calendarDay(to);if(!Number.isSafeInteger(maxDays)||maxDays<1)throw new ScheduleInputError("Invalid date-range limit");if(last<first)throw new ScheduleInputError("from must be on or before to");if(last-first+1>maxDays)throw new ScheduleInputError(`Generate at most ${maxDays} days at a time`);const schedule=parseWeeklySchedule(spec);if(!schedule)throw new ScheduleInputError("Invalid recurrence");const end=addClockMinutes(schedule.start_time,duration);const days=new Set(schedule.weekdays);const slots=[];for(let day=first;day<=last;day++){const date=new Date(day*DAY);if(days.has(date.getUTCDay()))slots.push({session_date:date.toISOString().slice(0,10),start_time:schedule.start_time,end_time:end})}return slots}export function timeWindowsCover(windows,start,end){const first=clockMinutes(start);const last=clockMinutes(end);const spans=windows.map((window)=>{const span={start:clockMinutes(window.start_time),end:clockMinutes(window.end_time)};if(span.end<=span.start)throw new ScheduleInputError("Availability must end after it starts");return span}).sort((a,b)=>a.start-b.start);if(first>=last)return false;let covered=first;for(const span of spans){if(span.start>covered)break;covered=Math.max(covered,span.end);if(covered>=last)return true}return false}export function localDateRange(from,to,...zones){const first=calendarDay(from);const last=calendarDay(to);if(last<first)throw new ScheduleInputError("from must be on or before to");if(Number(from.slice(0,4))<101||to>="9999-12-31")throw new ScheduleInputError("Local ranges support dates from 0101-01-01 through 9999-12-30");const timeZone=localDateTime(new Date(first*DAY),...zones).timeZone;const next=new Date((last+1)*DAY).toISOString().slice(0,10);return{start:zonedTimeToUtc(`${from}T00:00:00`,timeZone),end:zonedTimeToUtc(`${next}T00:00:00`,timeZone),timeZone}}export function netHoursBetween(start,end,breakMinutes=0){if(start==null||end==null||!Number.isFinite(breakMinutes))return 0;const first=start instanceof Date?start.getTime():Date.parse(start);const last=end instanceof Date?end.getTime():Date.parse(end);if(!Number.isFinite(first)||!Number.isFinite(last)||last<=first)return 0;return Math.max(0,(last-first)/3600000-Math.max(0,breakMinutes)/60)}export function localTimeSpan(date,start,end,...zones){const day=calendarDay(date);const first=clockMinutes(start);const last=clockMinutes(end);if(first===last)throw new ScheduleInputError("An interval must have distinct start and end times");if(Number(date.slice(0,4))<101||date>="9999-12-31")throw new ScheduleInputError("Unsupported local interval date");const timeZone=localDateTime(new Date(day*DAY),...zones).timeZone;const endDate=last<first?new Date((day+1)*DAY).toISOString().slice(0,10):date;const interval={start:zonedTimeToUtc(`${date}T${start}:00`,timeZone),end:zonedTimeToUtc(`${endDate}T${end}:00`,timeZone),timeZone};if(interval.end<=interval.start)throw new ScheduleInputError("The local interval has no positive duration in this timezone");return interval}export function timeSpansOverlap(first,second){for(const span of[first,second]){if(!Number.isFinite(span.start.getTime())||!Number.isFinite(span.end.getTime())||span.end<=span.start)throw new ScheduleInputError("An interval must contain a positive elapsed duration")}return first.start<second.end&&first.end>second.start}
package/dist/zone.js CHANGED
@@ -1 +1 @@
1
- import{zonedFormatter}from"./intl";import{dateFromParts}from"./parts";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",era:"short",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),year=parts.find((part)=>part.type==="era")?.value==="BC"?1-get("year"):get("year"),asUtc=dateFromParts(year,get("month")-1,get("day"),get("hour"),get("minute"),get("second"),0,!0).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=dateFromParts(Number(y),Number(mo)-1,Number(d),Number(h),Number(mi),Number(s),0,!0);if(!Number.isFinite(reading.getTime())||reading.getUTCFullYear()!==Number(y)||reading.getUTCMonth()+1!==Number(mo)||reading.getUTCDate()!==Number(d)||Number(h)>23||Number(mi)>59||Number(s)>59)throw RangeError("Invalid wall-clock calendar date or time");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,-5)}${sign}${pad(Math.floor(abs/60))}:${pad(abs%60)}`}
1
+ import{zonedFormatter}from"./intl";import{dateFromParts}from"./parts";const DAY_MS=86400000;const 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",era:"short",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(instant);const get=(type)=>Number(parts.find((p)=>p.type===type)?.value??0);const year=parts.find((part)=>part.type==="era")?.value==="BC"?1-get("year"):get("year");const reading=dateFromParts(year,get("month")-1,get("day"),get("hour"),get("minute"),get("second"),0,true);const asUtc=reading.getTime();const 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 new 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;const reading=dateFromParts(Number(y),Number(mo)-1,Number(d),Number(h),Number(mi),Number(s),0,true);if(!Number.isFinite(reading.getTime())||reading.getUTCFullYear()!==Number(y)||reading.getUTCMonth()+1!==Number(mo)||reading.getUTCDate()!==Number(d)||Number(h)>23||Number(mi)>59||Number(s)>59)throw new RangeError("Invalid wall-clock calendar date or time");const local=reading.getTime();const before=zoneOffsetMinutes(new Date(local-DAY_MS),timeZone);const after=zoneOffsetMinutes(new Date(local+DAY_MS),timeZone);const shows=(offset)=>{const instant=local-offset*60000;return zoneOffsetMinutes(new Date(instant),timeZone)===offset?instant:null};const 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);const local=new Date(Math.floor(instant.getTime()/1000)*1000+offset*60000);const sign=offset<0?"-":"+";const abs=Math.abs(offset);const pad=(n)=>String(n).padStart(2,"0");return`${local.toISOString().slice(0,-5)}${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.515",
4
+ "version": "0.75.518",
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.515"
62
+ "@stacksjs/utils": "0.75.518"
63
63
  },
64
64
  "sideEffects": false
65
65
  }