Skip to content

Commit e222fb2

Browse files
TimelyDiff Javascript Package
0 parents  commit e222fb2

File tree

3 files changed

+176
-0
lines changed

3 files changed

+176
-0
lines changed

README.md

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# TimelyDiff
2+
3+
TimelyDiff is a JavaScript package that converts Unix timestamps into human-readable time differences. It allows you to easily display the time difference between two points in time in a user-friendly manner.
4+
5+
[Installation](#installation) | [Usage](#usage) | [API](#API) | [Contribution](#Contribution)
6+
7+
### Installation
8+
To install TimelyDiff, you can use NPM:
9+
```shell
10+
npm i timelydiff
11+
```
12+
13+
Or, you can add it to your project's dependencies in your package.json file:
14+
```json
15+
"dependencies": {
16+
"timelydiff": "^1.0.0"
17+
}
18+
```
19+
<br>
20+
21+
### Usage
22+
To use TimelyDiff, you need to require it in your JavaScript file:
23+
```javascript
24+
const timelydiff = require('timelydiff').timelydiff;
25+
```
26+
Once you've required the function, you can use it to convert a Unix timestamp into a human-readable time difference:
27+
```javascript
28+
const timestamp = 1708868951000; // February 25th, 2024 08:24:36 AM UTC
29+
const timeDiff = timelydiff(timestamp);
30+
console.log(timeDiff); // "in 1 year"
31+
32+
const timestamp2 = 1667499433271;
33+
console.log(timelydiff(timestamp2)); // "4 months ago"
34+
```
35+
36+
> To generate a timestamp at the current moment and store it for later use, you can use the built-in JavaScript function Date.now(), which returns the number of milliseconds since January 1, 1970, 00:00:00 UTC (Unix timestamp).
37+
38+
<br>
39+
40+
Optionally, you can pass a second parameter to the function to specify the length of the output string. By default, the function will return a string in the format of x [unit] ago/in [x] [unit], but you can choose to return a shorter string by setting the length parameter to "short" or "shorter".
41+
42+
```javascript
43+
const timestamp = 1667499433271;
44+
const timeDiffShort = timelydiff(timestamp, "short");
45+
console.log(timeDiffShort); // "4mo ago"
46+
47+
//timelydiff(timestamp, "shorter") -> 4mo
48+
```
49+
50+
<br>
51+
52+
### API
53+
**`timelydiff(timestamp, length)`**
54+
Converts a Unix timestamp into a human-readable time difference.
55+
56+
Parameters
57+
- **`timestamp (number)`** - The Unix timestamp to convert.
58+
- **`length (string)`** - Optional. The length of the output string. Can be set to **`"short"`** or **`"shorter"`** to return a shorter string. Defaults to **`null`**.
59+
60+
Returns
61+
A string representing the time difference between the current time and the given timestamp.
62+
63+
<br>
64+
65+
### License
66+
TimelyDiff is released under the **MIT License**.
67+
68+
<br>
69+
70+
### Contribution
71+
Contributions are welcome and appreciated! If you have an idea for an improvement or a bug fix, please feel free to open an issue or submit a pull request. Before submitting a pull request, please ensure that your code follows the existing code style and has been thoroughly tested. Thank you for helping to make TimelyDiff even better!

index.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
//This function takes a Unix timestamp and an optional length parameter,
2+
//and returns a human-readable time difference in the past or future.
3+
function timelydiff(timestamp, length = null) {
4+
5+
//Calculate the time difference between the current time and the timestamp, in seconds.
6+
let timeDifference = (Date.now() - timestamp) / 1000;
7+
let timeDirection = null;
8+
9+
10+
//Determine whether the time difference is in the past or future (is negative)
11+
//and sets the timeDirection variable accordingly.
12+
//It also takes the absolute value of timeDifference in case it's negative.
13+
if (timeDifference < 0) {
14+
timeDifference = Math.abs(timeDifference);
15+
timeDirection = 'future';
16+
}
17+
else {
18+
timeDirection = 'past';
19+
}
20+
21+
22+
//This is an array of arrays, each containing three elements:
23+
//a unit of time (short and default),
24+
//the calculated value of that unit based on the timeDifference,
25+
//and the maximum value that unit can have 
26+
//(i.e. 60 seconds in a minute, 24 hours in a day, etc.).
27+
const timeUnits = [
28+
[{ short: 's', def: 'second' }, timeDifference, 60],
29+
[{ short: 'm', def: 'minute' }, Math.round(timeDifference / 60), 60],
30+
[{ short: 'h', def: 'hour' }, Math.round(timeDifference / 3600), 24],
31+
[{ short: 'd', def: 'day' }, Math.round(timeDifference / 86400), 7],
32+
[{ short: 'w', def: 'week' }, Math.round(timeDifference / 604800), 4],
33+
[{ short: 'mo', def: 'month' }, Math.round(timeDifference / 2419200), 12],
34+
[{ short: 'y', def: 'year' }, Math.round(timeDifference / 29030400), 10],
35+
[{ short: 'dcd', def: 'decade' }, Math.round(timeDifference / 290304000), Infinity]
36+
];
37+
38+
39+
//this helper function returns the time string with "in" or "ago" depending on the time direction.
40+
function positionTime(timeString) {
41+
if (timeDirection === 'future') {
42+
return `in ${timeString}`;
43+
} else {
44+
return `${timeString}${length === 'shorter' ? '' : ' ago'}`;
45+
}
46+
}
47+
48+
49+
//This is a for loop that iterates over each element in the timeUnits array.
50+
//It checks if the calculated value for that unit is less than the maximum value for that unit.
51+
//If so, it formats the output string using the positionTime helper function and the length parameter.
52+
//If the length parameter is null or longer, it returns the default format (e.g. "2 hours ago"),
53+
//and if the length parameter is "short" or "shorter",
54+
//it returns a shorter format (e.g. "2h" or "2 hours").
55+
for (const [name, value, range] of timeUnits) {
56+
57+
if (value < range) {
58+
let trunc = Math.trunc(value);
59+
60+
//if value > 1, pluralize by adding 's'
61+
let pluralize = trunc > 1 ? 's' : '';
62+
63+
if (length === null) {
64+
return positionTime(`${trunc} ${name.def}${pluralize}`);
65+
}
66+
67+
if (length === 'short' || length === 'shorter') {
68+
return positionTime(`${trunc}${name.short}`);
69+
}
70+
71+
break;
72+
}
73+
}
74+
75+
}
76+
77+
module.exports.timelydiff = timelydiff;

package.json

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
"name": "timelydiff",
3+
"version": "1.0.0",
4+
"description": "A JavaScript package that converts Unix timestamps into human-readable time differences.",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"repository": {
10+
"type": "git",
11+
"url": "git+https://github.com/artisticLogicMK/timelydiff.git"
12+
},
13+
"keywords": [
14+
"timelydiff",
15+
"time",
16+
"unix",
17+
"timestamp",
18+
"time",
19+
"difference",
20+
"date"
21+
],
22+
"author": "MK",
23+
"license": "MIT",
24+
"bugs": {
25+
"url": "https://github.com/artisticLogicMK/timelydiff/issues"
26+
},
27+
"homepage": "https://github.com/artisticLogicMK/timelydiff#readme"
28+
}

0 commit comments

Comments
 (0)