Files
BarangaySystem/resources/js/utils/date.js
2026-06-06 18:43:00 +08:00

106 lines
2.2 KiB
JavaScript

/**
* Converts a 24-hour time string to 12-hour format.
*
* @param {string} time24 - Time in HH:mm or HH:mm:ss format
* @returns {string} Time in 12-hour format (e.g. "3:45 PM")
*
* @example
* convertTo12HRTime('14:30') // "2:30 PM"
*/
export function convertTo12HRTime(time24) {
if (!time24) return ''
return new Date(`1970-01-01T${time24}Z`).toLocaleTimeString('en-US', {
timeZone: 'UTC',
hour: 'numeric',
minute: 'numeric',
hour12: true
})
}
/**
* Formats a Date object into "Mon DD, YYYY".
*
* @param {Date} date
* @returns {string}
*
* @example
* formatDate(new Date()) // "Jan 31, 2026"
*/
export function formatDate(date) {
if (!(date instanceof Date)) return ''
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
})
}
/**
* Returns today's date in GMT+8 timezone in "YYYY-MM-DD" format.
*
* @returns {string} - Date string in GMT+8
*
* @example
* getDateInGMT8() // "2026-01-31"
*/
export function getDateInGMT8() {
const now = new Date()
const utcTime = now.getTime()
const gmt8Offset = 8 * 60 * 60 * 1000
const gmt8Time = new Date(utcTime + gmt8Offset)
return gmt8Time.toISOString().split('T')[0]
}
/**
* Converts a date-time string into a readable format.
*
* Supports:
* - "YYYY-MM-DD"
* - "YYYY-MM-DD HH:mm:ss"
* - ISO strings
*
* @param {string} dateTimeString
* @returns {string}
*
* @example
* formatDateTimetoReadable('2026-01-31 14:30')
* // "January 31, 2026 2:30PM"
*/
export function formatDateTimetoReadable(dateTimeString) {
if (!dateTimeString) return ''
const normalized = dateTimeString.includes(' ')
? dateTimeString.replace(' ', 'T')
: dateTimeString
const date = new Date(normalized)
if (isNaN(date.getTime())) return ''
const datePart = date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
})
// Only show time if original string had time
if (!dateTimeString.includes(' ')) {
return datePart
}
let hours = date.getHours()
const minutes = date.getMinutes()
const ampm = hours >= 12 ? 'PM' : 'AM'
hours = hours % 12 || 12
const paddedMinutes = minutes.toString().padStart(2, '0')
return `${datePart} ${hours}:${paddedMinutes}${ampm}`
}