Skip to content

Commit

Permalink
feat: calculate the duration between two dates (across timezones) (#8)
Browse files Browse the repository at this point in the history
example: calculateDuration('2024-10-10', '2024-10-13', 'UTC', 'days') → 3 days
example: calculateDuration('2024-10-10', '2024-10-13', 'UTC', 'hours')-> 72 hours
example: calculateDuration('2024-10-10', '2024-10-13', 'UTC', 'minutes')-> 4320 minutes
  • Loading branch information
shivam-sharma7 authored Oct 15, 2024
1 parent 158f75e commit fe7c2d1
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 9 deletions.
30 changes: 24 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,8 @@ This is a lightweight and timezone-aware date utility package built on top of th
You can install the package via npm or yarn.

```bash
# npm
npm install world-clockify

# yarn
yarn add world-clockify

```
Expand All @@ -51,20 +49,40 @@ console.log(currentTime); // Outputs the current time in ISO format
const timeDifference = getTimeDifference('America/New_York', 'Europe/London');
console.log(timeDifference); // Outputs: 5 (hours)

// format date in a specific timezone
const dateStr = '2024-10-14T12:00:00';
const fromZone = 'UTC';
const toZone = 'America/New_York';
const format = 'MM/dd/yyyy HH:mm';

// Example usage:
console.log(formatDateInTimeZone(dateStr, fromZone, toZone, format)); //output: 10/14/2024 08:00

// Calculates the duration between two dates across timezones
const options = {
startDate: '2024-10-10',
endDate: '2024-10-13',
timezone: 'UTC',
unit: 'days',
};

// Calculate duration in days
const durationInDays = calculateDuration(options);
console.log(durationInDays); // Output: 3

// Calculate duration in hours
const durationInHours = calculateDuration({ ...options, unit: 'hours' });
console.log(durationInHours); // Output: 72

// Calculate duration in minutes
const durationInMinutes = calculateDuration({ ...options, unit: 'minutes' });
console.log(durationInMinutes); // Output: 4320
```

## Development

See [Contributing](./CONTRIBUTING.md).
See our [Contributing](./CONTRIBUTING.md).

## Support

Give a ⭐️ if this project helped you!
You can also sponsor me on [Github](https://github.com/sponsors/shivam-sharma7)
- Give a ⭐️ if this project helped you!
- You can also sponsor me on [Github](https://github.com/sponsors/shivam-sharma7)
39 changes: 38 additions & 1 deletion src/function.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DateTime, IANAZone } from 'luxon';
import { DateTime, IANAZone, Duration } from 'luxon';

/**
* Converts a date from one timezone to another.
Expand Down Expand Up @@ -135,3 +135,40 @@ export const formatDateInTimeZone = (dateStr: string, fromZone: string, toZone:

return formattedDate;
};

/**
* Calculates the duration between two dates across timezones.
* @param {string} startDateStr - The start date in string format (ISO).
* @param {string} endDateStr - The end date in string format (ISO).
* @param {string} timezone - The timezone in which the calculation is made.
* @returns {object} - The duration between the dates in days, hours, and minutes.
*/
export const calculateDuration = (
startDateStr: string,
endDateStr: string,
timezone: string,
unit: 'days' | 'hours' | 'minutes',
) => {
if (!IANAZone.isValidZone(timezone)) {
throw new Error(
`Invalid timezone: "${timezone}". Please provide a valid IANA timezone (e.g., 'America/New_York').`,
);
}

const startDate = DateTime.fromISO(startDateStr, { zone: timezone });
const endDate = DateTime.fromISO(endDateStr, { zone: timezone });

if (!startDate.isValid) {
throw new Error(`Invalid start date: "${startDateStr}". Ensure the date is in ISO format (e.g., 'YYYY-MM-DD').`);
}

if (!endDate.isValid) {
throw new Error(`Invalid end date: "${endDateStr}". Ensure the date is in ISO format (e.g., 'YYYY-MM-DD').`);
}

// Calculate difference in specified unit
const duration = endDate.diff(startDate, unit).as(unit);
console.log(`Difference between ${startDate.toString()} and ${endDate.toString()} in ${unit}:`, duration);

return duration;
};
27 changes: 25 additions & 2 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { describe, it, expect, should } from 'vitest';
import { convertTimeZone, getCurrentTimeInZone, getTimeDifference, formatDateInTimeZone } from '../src/function.js';
import { describe, it, expect } from 'vitest';
import {
convertTimeZone,
getCurrentTimeInZone,
getTimeDifference,
formatDateInTimeZone,
calculateDuration,
} from '../src/function.js';

describe('Timezone-Aware Date Helper', () => {
it('should convert date between timezones', () => {
Expand Down Expand Up @@ -40,4 +46,21 @@ describe('Timezone-Aware Date Helper', () => {
const result = formatDateInTimeZone(dateStr, fromZone, toZone, format);
expect(result).toBe('2024-10-14 21:00');
});

it('should calculates the duration between two dates across timezones ', () => {
const startDate = '2024-10-10';
const endDate = '2024-10-13';
const timezone = 'UTC';
const unitInDays = 'days';
const unitInHours = 'hours';
const unitInMinutes = 'minutes';

const durationInDays = calculateDuration(startDate, endDate, timezone, unitInDays);
const durationInHours = calculateDuration(startDate, endDate, timezone, unitInHours);
const durationInMinutes = calculateDuration(startDate, endDate, timezone, unitInMinutes);

expect(durationInDays).toBe(3); // 3 days difference
expect(durationInHours).toBe(72); // 3 days * 24 hours = 72 hours
expect(durationInMinutes).toBe(4320); // 72 hours * 60 minutes = 4320 minutes
});
});

0 comments on commit fe7c2d1

Please sign in to comment.