Skip to content

Commit

Permalink
Merge pull request #15 from jackie1santana/main
Browse files Browse the repository at this point in the history
Main
  • Loading branch information
jackie1santana authored Jul 18, 2024
2 parents 19e8342 + e530b18 commit 4c6af7f
Show file tree
Hide file tree
Showing 4 changed files with 180 additions and 33 deletions.
162 changes: 138 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,13 @@ outputs: `2022-07-02T23:12:01.449Z` _ISO date format_

**CDN 🌐**:
- https://cdn.jsdelivr.net/npm/showtimeago/index.js
- https://unpkg.com/browse/showtimeago/index.js
- https://unpkg.com/showtimeago@4.0.4/index.js

_This is essentially a CommonJS module, so you may ignore the error: Uncaught ReferenceError: module is not defined at showTimeAgo.js:115:1 on the client side._

**CDN Set up:**

`<script crossorigin type="text/javascript" src="https://unpkg.com/browse/showtimeago/index.js"></script>`
`<script crossorigin type="text/javascript" src="https://unpkg.com/showtimeago@4.0.4/index.js"></script>`
```
const showTimeAgo = showtimeago
Expand All @@ -73,51 +73,165 @@ console.log(showTimeAgo(new Date()))
___
#### By default, showTimeAgo updates only when the page is reloaded

_How to display showTimeAgo with real-time updates without reloading the page?_
# Time Ago Display Examples
___
## Node.js Example (with reload)

```javascript
const showTimeAgo = require('showtimeago');

**Vanilla Javascript Example:**
function updateTimeAgo() {
const showPastTime = showTimeAgo('2024-07-18T17:12:00.000Z');
console.clear(); // Clear the console
console.log(`Time ago: ${showPastTime}`);
}

```
// Initial update
updateTimeAgo();

// Update every minute
const intervalId = setInterval(updateTimeAgo, 60000);

// To stop the interval after a certain time (e.g., 1 hour):
// setTimeout(() => clearInterval(intervalId), 3600000);
```
## Node.js Example (with reload) writing to a file

```javascript
const showTimeAgo = require('showtimeago');
const fs = require('fs');

let showPastTime = showTimeAgo('2022-07-02T23:12:01.449Z')
const showTimeAgoToBrowser = document.querySelector('div')
showTimeAgoToBrowser.innerHTML = `${showPastTime}`;
function updateTimeAgo() {
const showPastTime = showTimeAgo('2024-07-18T17:12:00.000Z');
fs.writeFileSync('timeago.txt', `Time ago: ${showPastTime}`);
console.log(`Updated timeago.txt: ${showPastTime}`);
}

setInterval(() => {
showPastTime = showTimeAgo('2022-07-02T23:12:01.449Z')
showTimeAgoToBrowser.innerHTML = `${showPastTime}`;
// Initial update
updateTimeAgo();

// 600000 = 1 minute in ms
}, 60000)
// Update every minute
const intervalId = setInterval(updateTimeAgo, 60000);

clearInterval(showPastTime)
// To stop the interval after a certain time (e.g., 1 hour):
// setTimeout(() => clearInterval(intervalId), 3600000);
```
___
## Vanilla JavaScript Example

### HTML Setup
```html
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Time Ago Example</title>
</head>

<body>
<div id="timeAgoDisplay"></div>
<script src="https://cdn.jsdelivr.net/npm/showtimeago/index.js"></script>
<script src="script.js"></script>
</body>

</html>
```

### (without reload in Vanilla JS)

**React Example:**
```javascript
const showTimeAgo = window.showTimeAgo;

function updateTimeAgo() {
const showPastTime = showTimeAgo('2024-07-18T17:12:00.000Z');
const showTimeAgoToBrowser = document.getElementById('timeAgoDisplay');
showTimeAgoToBrowser.textContent = `Time ago: ${showPastTime}`;
}

// Initial update
updateTimeAgo();

// Update every minute without reloading the page
setInterval(updateTimeAgo, 60000);
```

### (with reload in Vanilla JS)

```javascript
const showTimeAgo = window.showTimeAgo;

function updateTimeAgo() {
const showPastTime = showTimeAgo('2024-07-18T17:12:00.000Z');
const showTimeAgoToBrowser = document.getElementById('timeAgoDisplay');
showTimeAgoToBrowser.innerHTML = `Time ago: ${showPastTime}`;
}

// Initial update
updateTimeAgo();

// Update every minute
setInterval(updateTimeAgo, 60000);
```
___
## React Example (with rerender)
```jsx
import * as React from "react";
import showTimeAgo from "showtimeago";

export default function App() {
const [showPastTime, setPastTime] = React.useState(null);

React.useEffect(() => {
function updateTimeAgo() {
setPastTime(showTimeAgo('2024-07-18T17:12:00.000Z'));
}

// Initial update
updateTimeAgo();

// Update every minute
const timer = setInterval(updateTimeAgo, 60000);

// Cleanup function
return () => clearInterval(timer);
}, []); // Empty dependency array means this effect runs once on mount

return <div>User Posted Comment {showPastTime}</div>;
}
```

## React Example (without rerender)

```jsx
import * as React from "react";
import showTimeAgo from "showtimeago";

export default function App() {
const [showPastTime, setPastTime] = React.useState(null);

React.useEffect(() => {
setPastTime(showTimeAgo('2022-07-02T23:12:01.449Z'));
function updateTimeAgo() {
const currentTime = showTimeAgo('2024-07-18T17:12:00.000Z');
if (currentTime !== showPastTime) {
setPastTime(currentTime);
}
}

const timer = window.setInterval(() => {
setPastTime(showTimeAgo('2022-07-02T23:12:01.449Z'));
// Initial update
updateTimeAgo();

// 600000 = 1 minute in ms
}, 60000);
// Update every minute without causing a re-render if the value hasn't changed
const timer = setInterval(updateTimeAgo, 60000);

return () => window.clearInterval(timer);
}, [showPastTime]);
// Cleanup function
return () => clearInterval(timer);
}, [showPastTime]); // Add showPastTime as a dependency

return <div>User Posted Comment { showPastTime }</div>;
return <div>User Posted Comment {showPastTime}</div>;
}
```
_With the code above, ShowTimeAgo will automatically update every minute without needing a page reload._

## Contributing 🤝
We welcome all contributions! If you have any cool ideas or features you think should be added, please:
Expand Down
3 changes: 0 additions & 3 deletions __test__/showTimeAgo.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,6 @@ test('Test Date for the start of Unix Epoch (January 1, 1970)', () => {
expect(showTimeAgo(epochStart)).toBe(`${epochYears} years ago`);
});

test('Test Date for a future date', () => {
expect(showTimeAgo(futureDate)).toBe('now');
});

test('Test Date for just a few seconds ago', () => {
expect(showTimeAgo(fewSecondsAgo)).toContain('seconds ago');
Expand Down
46 changes: 41 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ function showtimeago(dateParam) {
const year = date.getFullYear();
let hours = date.getHours();
let minutes = date.getMinutes();
const ampm = hours >= 12 ? 'pm' : 'am';
const ampm = hours >= 12 ? 'PM' : 'AM';

hours = hours % 12 || 12; // Convert hours to 12-hour format
minutes = minutes < 10 ? `0${minutes}` : minutes; // Add leading zero to minutes
Expand Down Expand Up @@ -56,11 +56,17 @@ function showtimeago(dateParam) {
function timeAgo(dateParam) {
const date = validateDateParam(dateParam);
const now = new Date();

// Check if the date is in the future
if (date > now) {
throw new Error("Invalid date: The provided date is in the future.");
}

const DAY_IN_MS = 86400000; // 24 * 60 * 60 * 1000
const YEAR_IN_MS = 365.25 * DAY_IN_MS; // Account for leap years
const yesterday = new Date(now - DAY_IN_MS);
const yesterday = new Date(now.getTime() - DAY_IN_MS);

const seconds = Math.round((now - date) / 1000);
const seconds = Math.round((now.getTime() - date.getTime()) / 1000);
const minutes = Math.round(seconds / 60);
const hours = Math.round(minutes / 60);
const days = Math.round(hours / 24);
Expand All @@ -76,8 +82,22 @@ function showtimeago(dateParam) {
return '1 year ago';
}

// Detailed logging for debugging
// console.log({
// seconds,
// minutes,
// hours,
// days,
// months,
// years,
// isToday,
// isYesterday,
// now,
// date
// });

switch (true) {
case (seconds < 5):
case (seconds < 2):
return 'now';
case (seconds < 60):
return `${seconds} seconds ago`;
Expand Down Expand Up @@ -116,4 +136,20 @@ function showtimeago(dateParam) {
}
}

module.exports = showtimeago;
// console.log(showtimeago("2024-07-18T17:12:00.000Z"));
// Example usage to test with current time
// const now = new Date();
// console.log("Current time:", now.toISOString());
// console.log("Result:", showtimeago(now));

// // Test with 5 seconds ago
// const fiveSecondsAgo = new Date(now.getTime() - 5000);
// console.log("5 seconds ago:", fiveSecondsAgo.toISOString());
// console.log("Result:", showtimeago(fiveSecondsAgo));

// // Test with 1 minute ago
// const oneMinuteAgo = new Date(now.getTime() - 60000);
// console.log("1 minute ago:", oneMinuteAgo.toISOString());
// console.log("Result:", showtimeago(oneMinuteAgo));

module.exports = showtimeago;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "showtimeago",
"version": "4.0.2",
"version": "4.0.5",
"description": "ShowTimeAgo is a utility that provides a human-readable format of how long ago a date was with zero configuration.",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit 4c6af7f

Please sign in to comment.