@orafavictor/date-difference-calculator 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +30 -0
- package/package.json +23 -0
- package/readme.md +116 -0
package/index.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
function calculateTimeDifference(targetDate) {
|
|
2
|
+
const currentDate = new Date();
|
|
3
|
+
const futureDate = new Date(targetDate);
|
|
4
|
+
|
|
5
|
+
if (isNaN(targetDate)){
|
|
6
|
+
throw new Error("Invalid date format");
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
if (futureDate <= currentDate) {
|
|
10
|
+
return {error: 'Date provided is in the past'};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const differenceInMillis = futureDate - currentDate;
|
|
14
|
+
|
|
15
|
+
const differenceInMinutes = Math.floor(differenceInMillis / (1000 * 60));
|
|
16
|
+
const differenceInHours = Math.floor(differenceInMillis / (1000 * 60 * 60));
|
|
17
|
+
const days = Math.floor(differenceInMinutes / (60 * 24));
|
|
18
|
+
const hours = Math.floor(differenceInMinutes % (60 * 24) / 60);
|
|
19
|
+
const minutes = Math.floor(differenceInMinutes % 60);
|
|
20
|
+
const seconds = Math.floor((differenceInMillis % (1000 * 60)) / 1000);
|
|
21
|
+
|
|
22
|
+
return {
|
|
23
|
+
days,
|
|
24
|
+
hours,
|
|
25
|
+
minutes,
|
|
26
|
+
seconds
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
module.exports = {calculateTimeDifference};
|
package/package.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@orafavictor/date-difference-calculator",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "A library to calculate the time difference between the curretn date and a provided date.",
|
|
5
|
+
"license": "ISC",
|
|
6
|
+
"author": "Rafael Victor",
|
|
7
|
+
"type": "commonjs",
|
|
8
|
+
"main": "index.js",
|
|
9
|
+
|
|
10
|
+
"scripts": {
|
|
11
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"date",
|
|
15
|
+
"difference",
|
|
16
|
+
"calculator",
|
|
17
|
+
"time",
|
|
18
|
+
"days",
|
|
19
|
+
"hours",
|
|
20
|
+
"minutes",
|
|
21
|
+
"seconds"
|
|
22
|
+
]
|
|
23
|
+
}
|
package/readme.md
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# Date Difference Calculator
|
|
2
|
+
|
|
3
|
+
Uma biblioteca leve e prática para calcular a diferença de tempo exata entre o momento atual e uma data futura. Ideal para criar contagens regressivas (countdowns), verificar prazos ou calcular tempo restante em dias, horas, minutos e segundos.
|
|
4
|
+
|
|
5
|
+
## 📋 Índice
|
|
6
|
+
|
|
7
|
+
- [Instalação](#instalação)
|
|
8
|
+
- [Como Usar](#como-usar)
|
|
9
|
+
- [Funcionalidades](#funcionalidades)
|
|
10
|
+
- [API](#api)
|
|
11
|
+
- [Tratamento de Erros](#tratamento-de-erros)
|
|
12
|
+
- [Autor](#autor)
|
|
13
|
+
- [Licença](#licença)
|
|
14
|
+
|
|
15
|
+
## 🚀 Instalação
|
|
16
|
+
|
|
17
|
+
Para instalar este pacote no seu projeto, execute o seguinte comando no terminal:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install date-difference-calculator
|
|
21
|
+
|
|
22
|
+
💻 Como Usar
|
|
23
|
+
A biblioteca exporta uma função principal chamada calculateTimeDifference. Você deve importar a função e passar a data alvo (futura) como argumento.
|
|
24
|
+
|
|
25
|
+
Aqui está um exemplo básico de como implementar:
|
|
26
|
+
|
|
27
|
+
JavaScript
|
|
28
|
+
const { calculateTimeDifference } = require('date-difference-calculator');
|
|
29
|
+
|
|
30
|
+
// Defina uma data futura (Ex: Ano Novo de 2026)
|
|
31
|
+
// Recomendamos passar um objeto Date ou um timestamp
|
|
32
|
+
const targetDate = new Date('2026-01-01T00:00:00');
|
|
33
|
+
|
|
34
|
+
try {
|
|
35
|
+
const timeRemaining = calculateTimeDifference(targetDate);
|
|
36
|
+
|
|
37
|
+
// Verifica se houve erro de data no passado
|
|
38
|
+
if (timeRemaining.error) {
|
|
39
|
+
console.log("Atenção:", timeRemaining.error);
|
|
40
|
+
} else {
|
|
41
|
+
console.log(`Faltam:
|
|
42
|
+
${timeRemaining.days} dias,
|
|
43
|
+
${timeRemaining.hours} horas,
|
|
44
|
+
${timeRemaining.minutes} minutos e
|
|
45
|
+
${timeRemaining.seconds} segundos.`);
|
|
46
|
+
}
|
|
47
|
+
} catch (err) {
|
|
48
|
+
console.error("Erro na data:", err.message);
|
|
49
|
+
}
|
|
50
|
+
✨ Funcionalidades
|
|
51
|
+
Cálculo Preciso: Retorna a diferença quebrada em dias, horas, minutos e segundos.
|
|
52
|
+
|
|
53
|
+
Validação de Data: Verifica se a data fornecida é válida.
|
|
54
|
+
|
|
55
|
+
Verificação de Passado: Identifica se a data alvo já passou e retorna uma mensagem amigável ao invés de números negativos.
|
|
56
|
+
|
|
57
|
+
📚 API
|
|
58
|
+
calculateTimeDifference(targetDate)
|
|
59
|
+
|
|
60
|
+
Calcula o tempo restante até a targetDate.
|
|
61
|
+
|
|
62
|
+
Parâmetros
|
|
63
|
+
|
|
64
|
+
Parâmetro Tipo Descrição
|
|
65
|
+
targetDate Date Number
|
|
66
|
+
Retorno
|
|
67
|
+
|
|
68
|
+
Retorna um Objeto contendo os seguintes campos:
|
|
69
|
+
|
|
70
|
+
JavaScript
|
|
71
|
+
{
|
|
72
|
+
days: number, // Dias restantes
|
|
73
|
+
hours: number, // Horas restantes (0-23)
|
|
74
|
+
minutes: number, // Minutos restantes (0-59)
|
|
75
|
+
seconds: number // Segundos restantes (0-59)
|
|
76
|
+
}
|
|
77
|
+
Caso a data seja no passado, o retorno será:
|
|
78
|
+
|
|
79
|
+
JavaScript
|
|
80
|
+
{
|
|
81
|
+
error: 'Date provided is in the past'
|
|
82
|
+
}
|
|
83
|
+
⚠️ Tratamento de Erros
|
|
84
|
+
A função lançará um erro (throw Error) se o formato da data for inválido (por exemplo, algo que não seja uma data ou número). Recomenda-se envolver a chamada da função em um bloco try...catch ou garantir que o input seja um objeto Date válido.
|
|
85
|
+
|
|
86
|
+
👤 Autor
|
|
87
|
+
Rafael Victor
|
|
88
|
+
|
|
89
|
+
Sinta-se à vontade para contribuir ou reportar problemas!
|
|
90
|
+
|
|
91
|
+
📄 Licença
|
|
92
|
+
Este projeto está sob a licença ISC.
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
### 💡 Dica Técnica (Opcional)
|
|
98
|
+
|
|
99
|
+
Notei um detalhe interessante no seu código no arquivo `index.js`:
|
|
100
|
+
|
|
101
|
+
```javascript
|
|
102
|
+
if (isNaN(targetDate)){
|
|
103
|
+
throw new Error("Invalid date format");
|
|
104
|
+
}
|
|
105
|
+
A função isNaN funciona bem para números e objetos Date, mas se o usuário tentar passar uma string diretamente (ex: "2025-12-25"), o isNaN retornará true e vai dar erro, mesmo a string sendo uma data válida.
|
|
106
|
+
|
|
107
|
+
Sugestão de melhoria para a versão 1.0.1: Se você quiser aceitar strings diretamente no futuro, você pode ajustar a validação para verificar a data depois de convertê-la:
|
|
108
|
+
|
|
109
|
+
JavaScript
|
|
110
|
+
// Exemplo de ajuste:
|
|
111
|
+
const futureDate = new Date(targetDate);
|
|
112
|
+
|
|
113
|
+
// Valida se a data criada é válida (Date inválido vira "Invalid Date", que é NaN em valor numérico)
|
|
114
|
+
if (isNaN(futureDate.getTime())) {
|
|
115
|
+
throw new Error("Invalid date format");
|
|
116
|
+
}
|