Skip to content

Commit

Permalink
feat: add validation for timezones with detailed error messages (#7)
Browse files Browse the repository at this point in the history
- Validate source and target timezones using IANAZone.isValidZone
- Provide clear error messages for invalid timezones
- Validate the date string and ensure it is in ISO format
- Add detailed logging for debugging purposes
  • Loading branch information
shivam-sharma7 authored Oct 15, 2024
1 parent a788458 commit 158f75e
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 6 deletions.
94 changes: 90 additions & 4 deletions src/function.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DateTime } from 'luxon';
import { DateTime, IANAZone } from 'luxon';

/**
* Converts a date from one timezone to another.
Expand All @@ -8,7 +8,36 @@ import { DateTime } from 'luxon';
* @returns {string} - The converted date in the target timezone.
*/
export const convertTimeZone = (dateStr: string, fromZone: string, toZone: string): string => {
return DateTime.fromISO(dateStr, { zone: fromZone }).setZone(toZone).toISO()!;
const dateTime = DateTime.fromISO(dateStr, { zone: fromZone });

// Debug: Print the original date with timezone info
console.log('Original DateTime:', dateTime.toString());

if (!IANAZone.isValidZone(fromZone)) {
throw new Error(
`Invalid source timezone: "${fromZone}". Please provide a valid IANA timezone (e.g., 'America/New_York').`,
);
}

// Validate the target timezone
if (!IANAZone.isValidZone(toZone)) {
throw new Error(
`Invalid target timezone: "${toZone}". Please provide a valid IANA timezone (e.g., 'Europe/London').`,
);
}

if (!dateTime.isValid) {
throw new Error(
`Invalid date string: "${dateStr}". Ensure the date is in ISO format (e.g., 'YYYY-MM-DDTHH:mm:ss').`,
);
}

const converted = dateTime.setZone(toZone);

// Debug: Print the converted date with timezone info
console.log('Converted DateTime:', converted.toString());

return converted.toISO()!;
};

/**
Expand All @@ -17,7 +46,20 @@ export const convertTimeZone = (dateStr: string, fromZone: string, toZone: strin
* @returns {string} - The current time in ISO format for the given timezone.
*/
export const getCurrentTimeInZone = (timezone: string): string => {
return DateTime.now().setZone(timezone).toISO()!;
if (!IANAZone.isValidZone(timezone)) {
throw new Error(
`Invalid timezone: "${timezone}". Please provide a valid IANA timezone (e.g., 'America/New_York').`,
);
}
// Get the current time in the specified timezone
const currentTime = DateTime.now().setZone(timezone);
console.log('Current DateTime in Zone:', currentTime.toString());

// Return the current time in ISO format
const currentTimeISO = currentTime.toISO();
console.log('Current DateTime in ISO Format:', currentTimeISO);

return currentTimeISO ?? '';
};

/**
Expand All @@ -27,12 +69,26 @@ export const getCurrentTimeInZone = (timezone: string): string => {
* @returns {number} - Time difference in hours.
*/
export const getTimeDifference = (timezone1: string, timezone2: string): number => {
if (!IANAZone.isValidZone(timezone1)) {
throw new Error(
`Invalid first timezone: "${timezone1}". Please provide a valid IANA timezone (e.g., 'America/New_York').`,
);
}

if (!IANAZone.isValidZone(timezone2)) {
throw new Error(
`Invalid second timezone: "${timezone2}". Please provide a valid IANA timezone (e.g., 'Asia/Kolkata').`,
);
}

const now = DateTime.now();
const zone1 = now.setZone(timezone1);
const zone2 = now.setZone(timezone2);

// Calculate the difference in offsets
const diffInHours = (zone2.offset - zone1.offset) / 60;
//Debug: Print differences
console.log(`Difference in offsets between ${timezone1} and ${timezone2} in hours is:`, diffInHours);

return diffInHours;
};
Expand All @@ -47,5 +103,35 @@ export const getTimeDifference = (timezone1: string, timezone2: string): number
*/

export const formatDateInTimeZone = (dateStr: string, fromZone: string, toZone: string, format: string): string => {
return DateTime.fromISO(dateStr, { zone: fromZone }).setZone(toZone).toFormat(format);
if (!IANAZone.isValidZone(fromZone)) {
throw new Error(
`Invalid source timezone: "${fromZone}". Please provide a valid IANA timezone (e.g., 'America/New_York').`,
);
}

if (!IANAZone.isValidZone(toZone)) {
throw new Error(
`Invalid target timezone: "${toZone}". Please provide a valid IANA timezone (e.g., 'Europe/London').`,
);
}

const dateTime = DateTime.fromISO(dateStr, { zone: fromZone });
console.log('Original DateTime:', dateTime.toString());

// Validate the date-time object
if (!dateTime.isValid) {
throw new Error(
`Invalid date string: "${dateStr}". Ensure the date is in ISO format (e.g., 'YYYY-MM-DDTHH:mm:ss').`,
);
}

// Convert to target timezone
const converted = dateTime.setZone(toZone);
console.log('Converted DateTime:', converted.toString());

// Format the converted date
const formattedDate = converted.toFormat(format);
console.log('Formatted DateTime:', formattedDate);

return formattedDate;
};
7 changes: 5 additions & 2 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ import { convertTimeZone, getCurrentTimeInZone, getTimeDifference, formatDateInT
describe('Timezone-Aware Date Helper', () => {
it('should convert date between timezones', () => {
const dateStr = '2024-01-01T12:00:00';
const converted = convertTimeZone(dateStr, 'America/New_York', 'Europe/London');
expect(converted).toBe('2024-01-01T17:00:00.000+00:00'); // Adjusted expected value
const fromZone = 'America/New_York';
const toZone = 'Europe/London';

const converted = convertTimeZone(dateStr, fromZone, toZone);
expect(converted).toBe('2024-01-01T17:00:00.000+00:00');
});

it('should get current time in a specific timezone', () => {
Expand Down

0 comments on commit 158f75e

Please sign in to comment.