| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!

View
 

date

Page history last edited by PBworks 17 years, 3 months ago

date

Para modificar a hora do sistema faça

   date MMDDhhmm

Onde MMDDhhmm = Mês Dia Hora Minutos

 

Para exibir a data tipo

Segunda 17 de janeiro de 2007 faça:

date "+%A %d de %B de %Y"

Para colocar o resultado acima em uma variável faça

 

var=$(date "+%A %d de %B de %Y")

 

Viajando no tempo

 

date -d yesterday +%d/%m/%Y

mostrará a data do dia anterior na formatação dd/mm/aaaa

 

date --date yesterday

mostra a data de ontem com a formatação do sistema. A opção --date pode ser substituída por -d e yesterday pode ser substituído por today, tomorrow dentre outras opções

 

 

Para saber que dia era a um mês atrás

date -d "-1 month" +%d/%m/%Y

 

Para saber que dia será daqui a dois meses

date -d "2 week"

 

Também podemos usar o termo "ago" para voltar dias

date -d "3 year ago"

 

+[FORMATO ] Define o formato da listagem que será usada pelo comando date. Os seguin-
    tes formatos são os mais usados:
       • %d - Dia do Mês (00-31).
       • %b - Dia do Mês abreviado tipo "jan"
       • %B - Dia do Mês completo tipo "janeiro"
       • %m - Mês do Ano (00-12).
       • %y - Ano (dois dígitos).
       • %Y - Ano (quatro dígitos).
       • %H - Hora (00-24).
       • %I - Hora (00-12).
       • %M - Minuto (00-59).
       • %j - Dia do ano (1-366).
       • %p - AM/PM (útil se utilizado com %d).
       • %r - Formato de 12 horas completo (hh:mm:ss AM/PM).
       • %T - Formato de 24 horas completo (hh:mm:ss).
       • %w - Dia da semana (0-6).

 

Alterando a data através de uma string

   date -s '17:30:25'

Na página de manual vemos que a opção '-s' indica a mudança da hora por uma string, ou seja, um texto entre aspas.

 

Acertando o relógio do hardware através de um comando

   /sbin/hwclock --systohc'' (or ``/sbin/hwclock --systohc --utc   

Outro modo interessante é:

  hwclock -w

 

Subtraindo datas

DATA=$(date +%Y%d)
 
echo $DATA 

DATA=$(expr $DATA - 1)

echo $DATA

 

Calculando o número de dias entre duas datas

Calculate number of days between two dates

#!/bin/bash
# days-between.sh:    Number of days between two dates.
# Usage: ./days-between.sh [M]M/[D]D/YYYY [M]M/[D]D/YYYY
#
# Note: Script modified to account for changes in Bash 2.05b
#+      that closed the loophole permitting large negative
#+      integer return values.

ARGS=2                # Two command line parameters expected.
E_PARAM_ERR=65        # Param error.

REFYR=1600            # Reference year.
CENTURY=100
DIY=365
ADJ_DIY=367           # Adjusted for leap year + fraction.
MIY=12
DIM=31
LEAPCYCLE=4

MAXRETVAL=255         #  Largest permissable
                      #+ positive return value from a function.

diff=                 # Declare global variable for date difference.
value=                # Declare global variable for absolute value.
day=                  # Declare globals for day, month, year.
month=
year=


Param_Error ()        # Command line parameters wrong.
{
  echo "Usage: `basename $0` [M]M/[D]D/YYYY [M]M/[D]D/YYYY"
  echo "       (date must be after 1/3/1600)"
  exit $E_PARAM_ERR
}  


Parse_Date ()                 # Parse date from command line params.
{
  month=${1%%/**}
  dm=${1%/**}                 # Day and month.
  day=${dm#*/}
  let "year = `basename $1`"  # Not a filename, but works just the same.
}  


check_date ()                 # Checks for invalid date(s) passed.
{
  [ "$day" -gt "$DIM" ] || [ "$month" -gt "$MIY" ] || [ "$year" -lt "$REFYR" ] && Param_Error
  # Exit script on bad value(s).
  # Uses "or-list / and-list".
  #
  # Exercise: Implement more rigorous date checking.
}


strip_leading_zero () #  Better to strip possible leading zero(s)
{                     #+ from day and/or month
  return ${1#0}       #+ since otherwise Bash will interpret them
}                     #+ as octal values (POSIX.2, sect 2.9.2.1).


day_index ()          # Gauss' Formula:
{                     # Days from Jan. 3, 1600 to date passed as param.

  day=$1
  month=$2
  year=$3

  let "month = $month - 2"
  if [ "$month" -le 0 ]
  then
    let "month += 12"
    let "year -= 1"
  fi  

  let "year -= $REFYR"
  let "indexyr = $year / $CENTURY"


  let "Days = $DIY*$year + $year/$LEAPCYCLE - $indexyr + $indexyr/$LEAPCYCLE + $ADJ_DIY*$month/$MIY + $day - $DIM"
  #  For an in-depth explanation of this algorithm, see
  #+ http://home.t-online.de/home/berndt.schwerdtfeger/cal.htm


  echo $Days

}  


calculate_difference ()            # Difference between two day indices.
{
  let "diff = $1 - $2"             # Global variable.
}  


abs ()                             #  Absolute value
{                                  #  Uses global "value" variable.
  if [ "$1" -lt 0 ]                #  If negative
  then                             #+ then
    let "value = 0 - $1"           #+ change sign,
  else                             #+ else
    let "value = $1"               #+ leave it alone.
  fi
}



if [ $# -ne "$ARGS" ]              # Require two command line params.
then
  Param_Error
fi  

Parse_Date $1
check_date $day $month $year       #  See if valid date.

strip_leading_zero $day            #  Remove any leading zeroes
day=$?                             #+ on day and/or month.
strip_leading_zero $month
month=$?

let "date1 = `day_index $day $month $year`"


Parse_Date $2
check_date $day $month $year

strip_leading_zero $day
day=$?
strip_leading_zero $month
month=$?

date2=$(day_index $day $month $year) # Command substitution.


calculate_difference $date1 $date2

abs $diff                            # Make sure it's positive.
diff=$value

echo $diff

exit 0
#  Compare this script with
#+ the implementation of Gauss' Formula in a C program at:
#+    http://buschencrew.hypermart.net/software/datedif

 

Referências

Comments (0)

You don't have permission to comment on this page.