Obtain hours, minutes and seconds from the date of birth

1

I do not know if the format of this script is correct or not. I would like to know if I am on the right track and if you could help me in two parameters that I lack and I can not get out.

Statement of the exercise: Ask the user date of birth, from it tell him the number of seconds, minutes and hours he has lived.

Code that I've done so far:

!/bin/bash 

read -p "Introduce tu fecha de nacimiento (formato: añomesdia) : " fecha

DIAS=$(( ($(date --date $fecha +%s) - $(date +%s) )/(60*60*24) ))
HORAS=$(( ($(date --date $fecha +%s) - $(date +%s) )/(60*60*24) ))

echo "Dias: $DIAS"
echo "Horas: $HORAS"
echo "Minutos: $MINUTOS"

I am not able to take the hours of difference between the date I enter and the current date, nor am I able to take minutes.

I imagine there will be a format to do it but I can not find it.

    
asked by ShJod 11.02.2018 в 18:35
source

2 answers

2

As the track3r solution does, the key here is to convert today's date and day's date of birth in unix timestap. That is, in the number of seconds that have passed since January 1, 1970, which is like the Big Bang unixero.

Therefore, the ideal would be to first normalize the received date, then convert both to unix timestamp, subtract one from the other and finally do the calculation:

#!/bin/bash

read -p "Introduce tu fecha de nacimiento (formato: añomesdia) : " fecha
hoy=$(date)

secs_hasta_fecha=$(date -d"$fecha" "+%s")  # esta fecha se da en la hora 00:00:00
secs_hasta_hoy=$(date -d"$hoy" "+%s")

# Calcula la diferencia en segundos entre las dos fechas dadas
dif=$((secs_hasta_hoy - secs_hasta_fecha))

# Calcula la diferencia en horas, minutos y segundos
horas=$((dif / 3600))
mins=$(( (dif - horas*3600) / 60))
segs=$((dif - horas*3600 - mins*60))

# Imprime el resultado
printf "la dif entre %s y hoy %s es de %d horas, %d minutos y %d segundos\n" "$fecha" "$hoy" "$horas" "$mins" "$segs"

Of your code, I can not stop commenting on a couple of things:

!/bin/bash   # <--- ¡falta # al principio!

# esto es correcto
read -p "Introduce tu fecha de nacimiento (formato: añomesdia) : " fecha

Probably instead of calculating the date each time, it is better to save it in a variable and then operate from there:

DIAS=$(( ($(date --date $fecha +%s) - $(date +%s) )/(60*60*24) ))
HORAS=$(( ($(date --date $fecha +%s) - $(date +%s) )/(60*60*24) ))

Besides that the variables are always recommended to be in lowercase, so that they do not collide with the environment variables, which by convention are written in uppercase.

echo "Dias: $DIAS"
echo "Horas: $HORAS"
echo "Minutos: $MINUTOS"
    
answered by 12.02.2018 в 15:17
1

Source: link

Value1='2016-10-13 14:19:23'
Value2='2016-10-18 10:34:58'
D1=$(date -d "$Value1" '+%s'); D2=$(date -d "$Value2" '+%s')
echo "$(((D2-D1)/86400)):$(date -u -d@$((D2-D1)) +%H:%M)"

It will be the exit:

4:20:15
    
answered by 11.02.2018 в 19:06