UNPKG

@robertocemeri/date-utils

Version:

A simple and lightweight JavaScript library for date and time operations with timezone support

209 lines (178 loc) 5.56 kB
class DateUtils { constructor(timezone = 'local') { this.timezone = timezone; } // Set timezone setTimezone(timezone) { this.timezone = timezone; return this; } // Get current date currentDate(format = 'YYYY-MM-DD') { const date = this._getDateInTimezone(); return this._formatDate(date, format); } // Get current year currentYear() { const date = this._getDateInTimezone(); return date.getFullYear(); } // Get current time currentTime(format = 'HH:mm:ss') { const date = this._getDateInTimezone(); return this._formatTime(date, format); } // Get current date and time currentDateTime(format = 'YYYY-MM-DD HH:mm:ss') { const date = this._getDateInTimezone(); return this._formatDateTime(date, format); } // Get timestamp timestamp() { return this._getDateInTimezone().getTime(); } // Private method to get date in specified timezone _getDateInTimezone() { const now = new Date(); if (this.timezone === 'local' || this.timezone === '') { return now; } if (this.timezone === 'utc') { return new Date(now.getTime() + (now.getTimezoneOffset() * 60000)); } // For other timezones, convert using Intl.DateTimeFormat try { const formatter = new Intl.DateTimeFormat('en-US', { timeZone: this.timezone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }); const parts = formatter.formatToParts(now); const partObject = {}; parts.forEach(part => { partObject[part.type] = part.value; }); return new Date( `${partObject.year}-${partObject.month}-${partObject.day}T${partObject.hour}:${partObject.minute}:${partObject.second}` ); } catch (error) { console.warn(`Invalid timezone: ${this.timezone}. Using local time.`); return now; } } // Private method to format date _formatDate(date, format) { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return format .replace('YYYY', year) .replace('MM', month) .replace('DD', day) .replace('YY', String(year).slice(-2)) .replace('M', date.getMonth() + 1) .replace('D', date.getDate()); } // Private method to format time _formatTime(date, format) { const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); const seconds = String(date.getSeconds()).padStart(2, '0'); const milliseconds = String(date.getMilliseconds()).padStart(3, '0'); return format .replace('HH', hours) .replace('mm', minutes) .replace('ss', seconds) .replace('SSS', milliseconds) .replace('H', date.getHours()) .replace('m', date.getMinutes()) .replace('s', date.getSeconds()); } // Private method to format date and time _formatDateTime(date, format) { const datePart = this._formatDate(date, format); return this._formatTime(date, datePart); } // Utility methods static getAvailableTimezones() { return Intl.supportedValuesOf('timeZone'); } // Add days to current date addDays(days) { const date = this._getDateInTimezone(); date.setDate(date.getDate() + days); return new DateUtils(this.timezone)._setCustomDate(date); } // Subtract days from current date subtractDays(days) { return this.addDays(-days); } // For internal use to set custom date _setCustomDate(date) { this._customDate = date; return this; } // Override _getDateInTimezone for custom dates _getDateInTimezone() { if (this._customDate) { const tempDate = this._customDate; this._customDate = null; return tempDate; } const now = new Date(); if (this.timezone === 'local' || this.timezone === '') { return now; } if (this.timezone === 'utc') { return new Date(now.getTime() + (now.getTimezoneOffset() * 60000)); } try { const formatter = new Intl.DateTimeFormat('en-US', { timeZone: this.timezone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }); const parts = formatter.formatToParts(now); const partObject = {}; parts.forEach(part => { partObject[part.type] = part.value; }); return new Date( `${partObject.year}-${partObject.month}-${partObject.day}T${partObject.hour}:${partObject.minute}:${partObject.second}` ); } catch (error) { console.warn(`Invalid timezone: ${this.timezone}. Using local time.`); return now; } } } // Factory function for easy creation function createDateUtils(timezone = 'local') { return new DateUtils(timezone); } // Convenience methods const currentDate = (format) => createDateUtils().currentDate(format); const currentYear = () => createDateUtils().currentYear(); const currentTime = (format) => createDateUtils().currentTime(format); const currentDateTime = (format) => createDateUtils().currentDateTime(format); const timestamp = () => createDateUtils().timestamp(); // Export everything export { DateUtils, createDateUtils, currentDate, currentYear, currentTime, currentDateTime, timestamp };