Equivalent output of PowerShell's get-date, but using bash [duplicate] - bash

I have a date in this format: "27 JUN 2011" and I want to convert it to 20110627
Is it possible to do in bash?

#since this was yesterday
date -dyesterday +%Y%m%d
#more precise, and more recommended
date -d'27 JUN 2011' +%Y%m%d
#assuming this is similar to yesterdays `date` question from you
#http://stackoverflow.com/q/6497525/638649
date -d'last-monday' +%Y%m%d
#going on #seth's comment you could do this
DATE="27 jun 2011"; date -d"$DATE" +%Y%m%d
#or a method to read it from stdin
read -p " Get date >> " DATE; printf " AS YYYYMMDD format >> %s" `date
-d"$DATE" +%Y%m%d`
#which then outputs the following:
#Get date >> 27 june 2011
#AS YYYYMMDD format >> 20110627
#if you really want to use awk
echo "27 june 2011" | awk '{print "date -d\""$1FS$2FS$3"\" +%Y%m%d"}' | bash
#note | bash just redirects awk's output to the shell to be executed
#FS is field separator, in this case you can use $0 to print the line
#But this is useful if you have more than one date on a line
More on Dates
note this only works on GNU date
I have read that:
Solaris version of date, which is unable
to support -d can be resolve with
replacing sunfreeware.com version of
date

On OSX, I'm using -f to specify the input format, -j to not attempt to set any date, and an output format specifier. For example:
$ date -j -f "%m/%d/%y %H:%M:%S %p" "8/22/15 8:15:00 am" +"%m%d%y"
082215
Your example:
$ date -j -f "%d %b %Y" "27 JUN 2011" +%Y%m%d
20110627

date -d "25 JUN 2011" +%Y%m%d
outputs
20110625

If you would like a bash function that works both on Mac OS X and Linux:
#
# Convert one date format to another
#
# Usage: convert_date_format <input_format> <date> <output_format>
#
# Example: convert_date_format '%b %d %T %Y %Z' 'Dec 10 17:30:05 2017 GMT' '%Y-%m-%d'
convert_date_format() {
local INPUT_FORMAT="$1"
local INPUT_DATE="$2"
local OUTPUT_FORMAT="$3"
local UNAME=$(uname)
if [[ "$UNAME" == "Darwin" ]]; then
# Mac OS X
date -j -f "$INPUT_FORMAT" "$INPUT_DATE" +"$OUTPUT_FORMAT"
elif [[ "$UNAME" == "Linux" ]]; then
# Linux
date -d "$INPUT_DATE" +"$OUTPUT_FORMAT"
else
# Unsupported system
echo "Unsupported system"
fi
}
# Example: 'Dec 10 17:30:05 2017 GMT' => '2017-12-10'
convert_date_format '%b %d %T %Y %Z' 'Dec 10 17:30:05 2017 GMT' '%Y-%m-%d'

Just with bash:
convert_date () {
local months=( JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC )
local i
for (( i=0; i<11; i++ )); do
[[ $2 = ${months[$i]} ]] && break
done
printf "%4d%02d%02d\n" $3 $(( i+1 )) $1
}
And invoke it like this
d=$( convert_date 27 JUN 2011 )
Or if the "old" date string is stored in a variable
d_old="27 JUN 2011"
d=$( convert_date $d_old ) # not quoted

It's enough to do:
data=`date`
datatime=`date -d "${data}" '+%Y%m%d'`
echo $datatime
20190206
If you want to add also the time you can use in that way
data=`date`
datatime=`date -d "${data}" '+%Y%m%d %T'`
echo $data
Wed Feb 6 03:57:15 EST 2019
echo $datatime
20190206 03:57:15

Maybe something changed since 2011 but this worked for me:
$ date +"%Y%m%d"
20150330
No need for the -d to get the same appearing result.

Related

Bash Comparing Time Stamps

I have bash script, where I'm looking at the git log of a file, and basically if the timestamp in the file is greater than the minus time i've specified, then alert me via slack, this sort of works, but not on a file which has a much older time stamp, code below;
#!/bin/bash
#Variables
NOW=$(date +"%a %b%Oe %H:%M:%S %Y")
MINUS=$(date +"%a %b%Oe %H:%M:%S %Y" --date '-10 min')
VALUEFILES=("helm/components/admin-ui/values" "helm/components/cssr/values")
#should run every 20minutes to catch any changes - also, once a change has been detected, get the author of the change to also send to slack notification
#git clone
#git clone xxx
cd xxx
#testing
echo "Time now with time -10mins"
echo "$NOW"
echo "$MINUS"
echo `pwd`
##########################
#functions
check_time_stamp_values () {
for f in "${VALUEFILES[#]}"; do
git log -- "$f".yaml > "$f".txt
grep "Date" "$f".txt | awk 'NR==1{ print $2, $3, $4, $5, $6 }' > "$f"-time.txt
echo "===================================================="
read -r firstline<"$f"-time.txt
if [ "$firstline" \> "$MINUS" ]
then
cat "$f"-time.txt
echo "$f.yaml has changed within the last 10minutes - sending slack notification"
echo "===================================================="
else
echo "===================================================="
cat "$f"-time.txt
echo "$f.yaml has not changed in the last 10minutes - no action required"
echo "===================================================="
fi
done
}
##########################
For the above, i get the below output;
Tue Nov 1 17:34:10 2022
Tue Nov 1 17:24:10 2022
====================================================
====================================================
Tue Nov 1 17:23:48 2022
values.yaml has not changed in the last 10minutes - no action required
====================================================
====================================================
Wed Oct 26 11:27:15 2022
helm/components/cssr/values.yaml has changed within the last 10minutes
====================================================
Anyone have any suggestions ? Many thanks
Solved this issue by doing the following;
NOW=$(date +"%Y-%m-%d %H:%M:%S")
MINUS=$(date +"%Y-%m-%d %H:%M:%S" --date '-10 min')
Change how the date is displayed, and also changed how the git log is displayed;
git log --date=format:'%Y-%m-%d %H:%M:%S' "$f".yaml > "$f".txt
Now works fine without any issues.

How to convert date in Macbook (Terminal)?

I need to convert the date of the macbook via CLI because I'm running a script:
Date we have to convert 2019-09-17 15:32:27
Final format Jun 17 15:32:27
I tried it with the following script:
date_raw=`grep "^.*,.*,.*,.*,.*,.*,"$i"," ${SNIFFER_BUFFER_USAGE} | head -1 | awk -F ',' '{ print $2}'`
if [ $OSX -eq 1 ];
then
dataHoraMinuto=$(date -j -f "%Y-%m-%d %H:%M:%S" "$date_raw" +"%b %d %H:%M:%S")
else
dataHoraMinuto=`date +"%b %d %H:%M:%S" -d "$date_raw"`
fi
$ date -d"2019-09-17 15:32:27" +"%b %d %T"
Sep 17 15:32:27

How to get the latest date for a specific day of the week in Bash [duplicate]

This question already has answers here:
How to find out the date of the last Saturday in Linux shell script or python?
(3 answers)
Closed 6 years ago.
Q: How can the latest date for a given_day_of_the_week?
Example: For example if today is the 2016-04-21, I just want to get the date for a given_day_of_the_week for example Monday which would be the 2016-04-18. This date will be still returned if the code was run tomorrow, up until the day before the following given_day_of_the_week.
Explanation: The code should return the latest given_day_of_the_week's (Monday) date until the Sunday 2016-04-24, then the same bit of code running will return the 2016-04-25 next week.
Requires GNU date:
today_dow=$(date +%w)
days=(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)
for ((dow=0; dow<7; dow++)); do
if ((dow < today_dow)); then
date -d "last ${days[dow]}"
else
date -d "${days[dow]}"
fi
done
Sun Apr 17 00:00:00 EDT 2016
Mon Apr 18 00:00:00 EDT 2016
Tue Apr 19 00:00:00 EDT 2016
Wed Apr 20 00:00:00 EDT 2016
Thu Apr 21 00:00:00 EDT 2016
Fri Apr 22 00:00:00 EDT 2016
Sat Apr 23 00:00:00 EDT 2016
So we can do:
given_day_of_the_week() {
local days=(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)
local today_dow=$(date +%w)
local dow datestr
for ((dow=0; dow<7; dow++)); do
if [[ "${days[dow],,}" == "${1,,}" ]]; then
if ((dow < today_dow)); then
datestr="last ${days[dow]}"
else
datestr="${days[dow]}"
fi
date -d "$datestr" "+%F"
fi
done
}
Resulting in:
$ given_day_of_the_week tuesday
2016-04-19
$ given_day_of_the_week friday
2016-04-22
Hardcoding the weekday names like that will give you problems if you're in a different locale
Responding to #ryenus's comment:
$ given_day_of_the_week() {
local -A days=([sunday]=0 [monday]=1 [tuesday]=2 [wednesday]=3 [thursday]=4 [friday]=5 [saturday]=6)
local today_dow=$(date +%w)
local datestr=${1,,}
local dow=${days[$datestr]}
[[ -z "$dow" ]] && { echo "error: unknown day: '$1'" >&2; return 1; }
(( dow < today_dow )) && datestr="last $datestr"
date -d "$datestr" "+%F"
}
$ given_day_of_the_week friday
2016-04-22
$ given_day_of_the_week monday
2016-04-18
$ given_day_of_the_week FOO
error: unknown day: 'FOO'
Inspired by #glenn-jackman's answer, but simpler:
given_day_of_the_week=$1
f='%A %Y-%m-%d'
tomorrow=`date -d 'tomorrow' +"$f"`
today=`date -d 'today' +"$f"`
last5=`seq 1 5 | xargs -I{} date -d '{} day ago' +"$f"`
echo -e "$tomorrow\n$today\n$last5" |
grep -i $given_day_of_the_week |
cut -d' ' -f2
Note: this answer does give tomorrow's date for Monday if used on a Sunday. It also gives tomorrow's date for Tuesday if used on a Monday. Not 100% sure if that's what you had in mind.
If instead the idea is to always go with the current Sunday - Saturday, this will do it:
given_day_of_the_week=$1
f='%A %Y-%m-%d'
[ `date +%A` = 'Sunday' ] && first=`date -d 'today' +"$f"` ||
first=`date -d 'last Sunday' +"$f"`
rest=`seq 1 6 | xargs -I{} date -d "$first +{} day" +"$f"`
echo -e "$first\n$rest" |
grep -i $given_day_of_the_week |
cut -d' ' -f2
# requires bash 4.x and GNU date
last_kday() {
local kday=$1
local -A numbers=([sunday]=0 [monday]=1 [tuesday]=2 [wednesday]=3
[thursday]=4 [friday]=5 [saturday]=6)
if [[ $kday == *day ]]; then
kday=${numbers[${kday,,}]}
elif [[ $kday != [0-6] ]]; then
echo >&2 "Usage: last_kday weekday"
return 1
fi
local today=$(date +%w)
local days_ago=$(( today - kday ))
if (( days_ago < 0 )); then let days_ago+=7; fi
date -d "$days_ago days ago" +%F
}

Get the date (a day before current time) in Bash

How can I print the date which is a day before current time in Bash?
if you have GNU date and i understood you correctly
$ date +%Y:%m:%d -d "yesterday"
2009:11:09
or
$ date +%Y:%m:%d -d "1 day ago"
2009:11:09
If you have BSD (OSX) date you can do it like this:
date -j -v-1d
Wed Dec 14 15:34:14 CET 2011
Or if you want to do date calculations on an arbitrary date:
date -j -v-1d -f "%Y-%m-%d" "2011-09-01" "+%Y-%m-%d"
2011-08-31
date --date='-1 day'
MAC OSX
For yesterday's date:
date -v-1d +%F
where 1d defines current day minus 1 day. Similarly,
date -v-1w +%F - for previous week date
date -v-1m +%F - for previous month date
IF YOU HAVE GNU DATE,
date --date="1 day ago"
More info: https://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html
Sorry not mentioning I on Solaris system.
As such, the -date switch is not available on Solaris bash.
I find out I can get the previous date with little trick on timezone.
DATE=`TZ=MYT+16 date +%Y-%m-%d_%r`
echo $DATE
Well this is a late answer,but this seems to work!!
YESTERDAY=`TZ=GMT+24 date +%d-%m-%Y`;
echo $YESTERDAY;
Advanced Bash-scripting Guide
date +%Y:%m:%d -d "yesterday"
For details about the date format see the man page for date
date --date='-1 day'
date -d "yesterday" '+%Y-%m-%d'
or
date=$(date -d "yesterday" '+%Y-%m-%d')
echo $date
Use Perl instead perhaps?
perl -e 'print scalar localtime( time - 86400 ) . "\n";'
Or, use nawk and (ab)use /usr/bin/adb:
nawk 'BEGIN{printf "0t%d=Y\n", srand()-86400}' | adb
Came across this too ... insane!
/usr/bin/truss /usr/bin/date 2>&1 | nawk -F= '/^time\(\)/ {gsub(/ /,"",$2);printf "0t%d=Y\n", $2-86400}' | adb
date --date='-1 day'
Not very sexy but might do the job:
perl -e 'my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time - 86400);$year += 1900; $mon+= 1; printf ("YESTERDAY: %04d%02d%02d \n", $year, $mon, $mday)'
Formated from "martin clayton" answer.
You could do a simple calculation, pimped with an regex, if the chosen date format is 'YYYYMM':
echo $(($(date +"%Y%m") - 1)) | sed -e 's/99$/12/'
In January of 2020 it will return 201912 ;-)
But, it's only a workaround, when date does not have calculation options and other dateinterpreter options (e.g. using perl) not available ;-)
short answer (GNU format):
date +%Y-%m-%d -d "-2 day"
if you are using OSX, but you need create for GNU compatible, install coreutils first
brew install coreutils
then edit your profile with:
#gnu coreutils first
export PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
re-start your terminal, and now you able to use GNU format!
yesterday=`date -d "-1 day" %F`
Puts yesterday's date in YYYY-MM-DD format into variable $yesterday.
#!/bin/bash
OFFSET=1;
eval `date "+day=%d; month=%m; year=%Y"`
# Subtract offset from day, if it goes below one use 'cal'
# to determine the number of days in the previous month.
day=`expr $day - $OFFSET`
if [ $day -le 0 ] ;then
month=`expr $month - 1`
if [ $month -eq 0 ] ;then
year=`expr $year - 1`
month=12
fi
set `cal $month $year`
xday=${$#}
day=`expr $xday + $day`
fi
echo $year-$month-$day
DST aware solution:
Manipulating the Timezone is possible for changing the clock some hours. Due to the daylight saving time, 24 hours ago can be today or the day before yesterday.
You are sure that yesterday is 20 or 30 hours ago. Which one? Well, the most recent one that is not today.
echo -e "$(TZ=GMT+30 date +%Y-%m-%d)\n$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1
The -e parameter used in the echo command is needed with bash, but will not work with ksh. In ksh you can use the same command without the -e flag.
When your script will be used in different environments, you can start the script with #!/bin/ksh or #!/bin/bash. You could also replace the \n by a newline:
echo "$(TZ=GMT+30 date +%Y-%m-%d)
$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1
Try the below code , which takes care of the DST part as well.
if [ $(date +%w) -eq $(date -u +%w) ]; then
tz=$(( 10#$gmthour - 10#$localhour ))
else
tz=$(( 24 - 10#$gmthour + 10#$localhour ))
fi
echo $tz
myTime=`TZ=GMT+$tz date +'%Y%m%d'`
Courtsey Ansgar Wiechers
date +%Y:%m:%d|awk -vFS=":" -vOFS=":" '{$3=$3-1;print}'
2009:11:9

YYYY-MM-DD format date in shell script

I tried using $(date) in my bash shell script, however, I want the date in YYYY-MM-DD format.
How do I get this?
In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external date (usually GNU date).
As such:
# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1
# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1
# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal
In bash (<4.2):
# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')
# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')
# print current date directly
echo $(date '+%Y-%m-%d')
Other available date formats can be viewed from the date man pages (for external non-bash specific command):
man date
Try: $(date +%F)
The %F option is an alias for %Y-%m-%d
You can do something like this:
$ date +'%Y-%m-%d'
$(date +%F)
output
2018-06-20
Or if you also want time:
$(date +%F_%H-%M-%S)
can be used to remove colons (:) in between
output
2018-06-20_09-55-58
You're looking for ISO 8601 standard date format, so if you have GNU date (or any date command more modern than 1988) just do: $(date -I)
date -d '1 hour ago' '+%Y-%m-%d'
The output would be 2015-06-14.
With recent Bash (version ≥ 4.2), you can use the builtin printf with the format modifier %(strftime_format)T:
$ printf '%(%Y-%m-%d)T\n' -1 # Get YYYY-MM-DD (-1 stands for "current time")
2017-11-10
$ printf '%(%F)T\n' -1 # Synonym of the above
2017-11-10
$ printf -v date '%(%F)T' -1 # Capture as var $date
printf is much faster than date since it's a Bash builtin while date is an external command.
As well, printf -v date ... is faster than date=$(printf ...) since it doesn't require forking a subshell.
I use the following formulation:
TODAY=`date -I`
echo $TODAY
Checkout the man page for date, there is a number of other useful options:
man date
if you want the year in a two number format such as 17 rather than 2017, do the following:
DATE=`date +%d-%m-%y`
I use $(date +"%Y-%m-%d") or $(date +"%Y-%m-%d %T") with time and hours.
I used below method. Thanks for all methods/answers
ubuntu#apj:/tmp$ datevar=$(date +'%Y-%m-%d : %H-%M')
ubuntu#apj:/tmp$ echo $datevar
2022-03-31 : 10-48
Whenever I have a task like this I end up falling back to
$ man strftime
to remind myself of all the possibilities for time formatting options.
Try to use this command :
date | cut -d " " -f2-4 | tr " " "-"
The output would be like: 21-Feb-2021
#!/bin/bash -e
x='2018-01-18 10:00:00'
a=$(date -d "$x")
b=$(date -d "$a 10 min" "+%Y-%m-%d %H:%M:%S")
c=$(date -d "$b 10 min" "+%Y-%m-%d %H:%M:%S")
#date -d "$a 30 min" "+%Y-%m-%d %H:%M:%S"
echo Entered Date is $x
echo Second Date is $b
echo Third Date is $c
Here x is sample date used & then example displays both formatting of data as well as getting dates 10 mins more then current date.
You can set date as environment variable and later u can use it
setenv DATE `date "+%Y-%m-%d"`
echo "----------- ${DATE} -------------"
or
DATE =`date "+%Y-%m-%d"`
echo "----------- ${DATE} -------------"
echo "`date "+%F"`"
Will print YYYY-MM-DD
Try this code for a simple human readable timestamp:
dt=$(date)
echo $dt
Output:
Tue May 3 08:48:47 IST 2022

Resources