@kadconsulting/dry
Version:
KAD Reusable Component Library
307 lines • 12.9 kB
JavaScript
// @ts-nocheck
import { format } from 'date-fns';
import moment from 'moment-timezone';
/**
* Converts a given date to the specified time zone, only if it's not already in that time zone.
* @param {Date | string | number} date - The date to be converted.
* @param {string} timeZone - The target time zone.
* @returns {Date} - The converted date as a Date object.
*/
export const convertToTimeZoneIfNeeded = (date, timeZone = 'America/Denver') => {
const momentDate = moment(date);
const isAlreadyInTimeZone = momentDate.tz(timeZone).format('Z') === momentDate.format('Z');
if (isAlreadyInTimeZone) {
return momentDate.toDate();
}
return momentDate.tz(timeZone).toDate();
};
export const formatDateToLocaleString = (date) => {
return format(date, 'MM/dd/yyyy HH:mm');
};
export const formatDateToLocaleStringFromISO = (isoDateStr) => {
// Parse the ISO string without converting it to local time
const momentDate = moment.parseZone(isoDateStr);
// Format the date, maintaining the original timezone offset
return momentDate.format('MM/DD/YYYY HH:mm');
};
export const formatDateToLocaleAmPmStringFromISO = (isoDateStr) => {
// Parse the ISO string without converting it to local time
const momentDate = moment.parseZone(isoDateStr);
// Format the date, maintaining the original timezone offset
return momentDate.format('MM/DD/YYYY hh:mm A');
};
export const formatBookingDateTime = (bookingDateTime, format = 'MM/dd hh:mm a', timeZone = 'America/Denver') => {
return moment(bookingDateTime).tz(timeZone).format(format);
};
// /**
// * Formats a given date string as an ISO string while keeping it in the 'America/Denver' timezone.
// *
// * @param {string} dateString - The date string in "MM/DD/YYYY HH:mm" format, assumed to be in Denver time.
// * @returns {string} - The formatted ISO string representing the same time in the Denver timezone.
// */
// const = formatAsISOInDenverTimezone(dateString) =>{
// // Parse the date in the Denver timezone context
// const dateInDenver = moment.tz(dateString, "MM/DD/YYYY HH:mm", "America/Denver");
// // Format the date as an ISO string while keeping it in the Denver timezone
// return dateInDenver.format(); // This uses the default moment format, which includes timezone information.
// }
/**
* Converts a given Denver time date string to a UTC ISO string with the time preserved.
*
* @param {string} dateString - The date string in "MM/DD/YYYY HH:mm" format, assumed to be in Denver time.
* @returns {string} - A UTC ISO string with the time preserved as in the input.
*/
export const convertDenverTimeToISOWithTimePreserved = (dateString) => {
// Parse the date as given, assuming it's in Denver time
const dateInDenver = moment.tz(dateString, 'MM/DD/YYYY HH:mm', 'America/Denver');
// Convert the time to UTC without changing the time values
const dateInUTCWithTimePreserved = moment.utc(dateInDenver.format('YYYY-MM-DDTHH:mm:ss.SSS'));
// Return the ISO string representation
return dateInUTCWithTimePreserved.toISOString(); // This keeps the time as is but appends "Z" to indicate UTC
};
export const convertTimeToISO = (timeString) => {
let datePart, timePart;
// Check if the string contains the 'T' character, typical for ISO strings
if (timeString.includes('T')) {
[datePart, timePart] = timeString.split('T');
}
else if (timeString.includes('/')) {
// Handle 'MM/DD/YYYY HH:MM' format
[datePart, timePart] = timeString.split(' ');
let [month, day, year] = datePart.split('/').map(Number);
datePart = `${year}-${month}-${day}`;
}
else {
// Assume 'YYYY-MM-DD hh:mm:ss' format if no 'T' and not in 'MM/DD/YYYY' format
datePart = timeString.substring(0, 10); // 'YYYY-MM-DD'
timePart = timeString.substring(11, 19); // 'hh:mm:ss'
}
// Normalize time part: remove any extraneous parts (like milliseconds or timezone info)
timePart = timePart.split('.')[0].split('Z')[0];
// Extract year, month, and day from the date part
const [year, month, day] = datePart.split('-').map(Number);
// Extract hours and minutes from the time part
const [hours, minutes] = timePart.split(':').map(Number);
// Create a new Date object using local time values
const formattedTime = new Date(Date.UTC(year, month - 1, day, hours, minutes));
// Return the ISO string of the UTC time
return formattedTime.toISOString();
};
export const removeTimezoneFromISO = (isoString) => {
// Normalize time part: remove any extraneous parts (like milliseconds or timezone info)
return isoString.split('.')[0].split('Z')[0];
};
/**
* Appends UTC designator to a given time string without altering the time.
*
* @param {string} timeString - The time string in "HH:mm:ss" format.
* @returns {string} - The input time string with UTC timezone information appended.
*/
export const convertTimeToUTC = (timeString) => {
// Check if the time string already includes milliseconds
if (!/\.\d{3}/.test(timeString)) {
// If milliseconds are missing, add ".000" to represent milliseconds
timeString += '.000';
}
// Append 'Z' to indicate UTC time zone without altering the original time components
return timeString;
};
export const addDurationToDateTime = ({ startDateTime, duration, }) => {
const [date, time] = startDateTime.split(', ');
const [hours, minutes, seconds] = time.slice(0, -3).split(':');
const period = time.slice(-2);
let totalMinutes = parseInt(minutes) + (duration % 60);
let totalHours = parseInt(hours) + Math.floor(duration / 60);
if (totalMinutes >= 60) {
totalHours += Math.floor(totalMinutes / 60);
totalMinutes = totalMinutes % 60;
}
if (period === 'AM' && totalHours >= 12) {
totalHours = totalHours % 12;
if (totalHours === 0)
totalHours = 12;
}
else if (period === 'PM' && totalHours >= 12) {
totalHours = (totalHours % 12) + 12;
if (totalHours === 24) {
totalHours = 0;
// Increment the date by one day
const [month, day, year] = date.split('/');
const currentDate = new Date(`${year}-${month}-${day}`);
const nextDay = new Date(currentDate);
nextDay.setDate(currentDate.getDate() + 1);
const formattedDate = `${nextDay.getMonth() + 1}/${nextDay.getDate()}/${nextDay.getFullYear()}`;
return `${formattedDate}, ${totalHours
.toString()
.padStart(2, '0')}:${totalMinutes
.toString()
.padStart(2, '0')}:${seconds} ${period}`;
}
}
return `${date}, ${totalHours.toString().padStart(2, '0')}:${totalMinutes
.toString()
.padStart(2, '0')}:${seconds} ${period}`;
};
export const convertToDenverTime = (date) => {
const formattedDate = date.toLocaleDateString('en-US', {
month: 'numeric',
day: 'numeric',
year: 'numeric',
});
const formattedTime = date.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: true,
});
const formattedDateTime = `${formattedDate}, ${formattedTime}`;
return formattedDateTime;
};
export const formatTimeString = (dateTimeString) => {
if (!dateTimeString || !dateTimeString.length)
return '';
const [_, time, period] = dateTimeString.split(/,?\s+/);
const [hours, minutes] = time.split(':');
let formattedHours = parseInt(hours, 10);
const formattedMinutes = minutes.padStart(2, '0');
if (period.toLowerCase() === 'pm' && formattedHours !== 12) {
formattedHours += 12;
}
else if (period.toLowerCase() === 'am' && formattedHours === 12) {
formattedHours = 0;
}
return `${formattedHours.toString().padStart(2, '0')}:${formattedMinutes}`;
};
const convertMilitaryTimeToAmPm = (militaryTime) => {
const [hours, minutes] = militaryTime.split(':');
const formattedHours = parseInt(hours, 10);
const formattedMinutes = minutes.padStart(2, '0');
const period = formattedHours < 12 ? 'AM' : 'PM';
const displayHours = formattedHours % 12 || 12;
return `${displayHours}:${formattedMinutes} ${period}`;
};
const convertMonthToNumber = (month) => {
const monthNames = [
'january',
'february',
'march',
'april',
'may',
'june',
'july',
'august',
'september',
'october',
'november',
'december',
];
return monthNames.indexOf(month.toLowerCase()) + 1;
};
export const convertTime = (timeString) => {
if (!timeString) {
return '';
}
// => 2024-04-03T20:00:00
let datePart, timePart;
// Check if the string contains the 'T' character, typical for ISO strings
if (timeString.includes('T')) {
[datePart, timePart] = timeString.split('T');
}
else {
return null;
}
// Extract year, month, and day from the date part
const [year, month, day] = datePart.split('-').map(Number);
const formattedTime = `${month}/${day}/${year}, ${convertMilitaryTimeToAmPm(timePart)}`;
// =>'4/28/2024, 10:00:00 PM'
return formattedTime;
};
export const formatTimeStringWhole = (dateTimeString) => {
// => "Wed May 01 2024 16:00:00 GMT-0400 (Eastern Daylight Time)"
if (!dateTimeString || !dateTimeString.length)
return '';
const [day, month, date, year, time] = dateTimeString
.split('GMT')[0]
.trim()
.split(' '); // => "Wed May 01 2024 16:00:00"
const formattedTime = `${convertMonthToNumber(month)}/${date}/${year}, ${convertMilitaryTimeToAmPm(time)}`;
// =>'4/28/2024, 10:00:00 PM'
return formattedTime;
};
export const convertToDenverTimeWithAmPM = (dateTimeString) => {
// => '4/28/2024, 10:00:00 PM'
if (!dateTimeString) {
return '';
}
const format = formatTimeString(dateTimeString); // => "12:00"
const [date, time] = dateTimeString.split(', '); // => ['4/28/2024', '10:00:00 PM']
const formattedTime = `${format}:00`;
const timeConversion = convertDenverTimeToISOWithTimePreserved(`${date}, ${formattedTime}`);
if (timeConversion) {
return timeConversion;
}
};
// input => "5/28/2024, 10:00 AM"
// output => "May 8, 2024 - 9:00 AM"
export const formatDate = (dateString) => {
if (dateString === null || dateString === '')
return '';
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
const [datePart, timePart] = dateString.split(', ');
const [month, day, year] = datePart.split('/');
let [hour, minute] = timePart.split(':');
const ampm = timePart.slice(-2);
// Convert hour to 12-hour format
let formattedHour = parseInt(hour, 10);
if (ampm === 'PM' && formattedHour !== 12) {
formattedHour += 12;
}
else if (ampm === 'AM' && formattedHour === 12) {
formattedHour = 0;
}
// Format the hour and minute with leading zeros if necessary
const formattedHourString = formattedHour.toString().padStart(2, '0');
const formattedMinute = minute.padStart(2, '0');
// Get the month name from the month array
const monthName = months[parseInt(month, 10) - 1];
// Remove the leading zero from the day if present
const formattedDay = day.replace(/^0/, '');
// Combine the formatted date and time parts
const formattedDateTime = `${monthName} ${formattedDay}, ${year} - ${formattedHourString}:${formattedMinute} ${ampm}`;
return formattedDateTime;
};
export const isoUtc = (isoString) => {
let datePart, timePart;
// Check if the string contains the 'T' character, typical for ISO strings
if (isoString.includes('T')) {
[datePart, timePart] = isoString.split('T');
}
else {
// Handle cases where the input might not be in standard ISO format
datePart = isoString.substring(0, 10); // Assuming 'YYYY-MM-DD' format
timePart = isoString.substring(11, 19); // Assuming 'hh:mm:ss' format
}
// Remove any extraneous parts from time (like milliseconds or timezone info)
timePart = timePart.split('.')[0].split('Z')[0];
// Extract year, month, and day from the date part
const [year, month, day] = datePart.split('-').map(Number);
// Extract hours and minutes from the time part
const [hours, minutes] = timePart.split(':').map(Number);
// Create a new Date object using local time values
const formattedTime = new Date(year, month - 1, day, hours, minutes);
return formattedTime;
};
//# sourceMappingURL=dateUtils.js.map