Exactly as the question sounds. I want to subtract say 20120115 from 20120203 and get 19 as the answer. What is the best way to implement this in a shell script?
相关问题
- Is shmid returned by shmget() unique across proces
- how to get running process information in java?
- JQ: Select when attribute value exists in a bash a
- Date with SimpleDateFormat in Java
- Error building gcc 4.8.3 from source: libstdc++.so
How I solved this is: (hope this eventually contains some more useful stuff)
date +%s.%N -d $1
takes an arbitrary date and converts it to the given format.To convert it back to human-readable, you can use
Where $2 is a date format see https://www.tutorialkart.com/bash-shell-scripting/bash-date-format-options-examples/
A quick and utterly dirty fix that can be used in scripts (quick and also fast):
This function
gendates
generates a list of valid dates between two dates in YYYYmmdd format (oldest first).I use this function for several purposes related to log files, like generating a list of logfile names to check [1]. And it comes handy to count the difference in days too:
YYYYmmdd have to be dates, of course. It only works if $1 is an earlier date than $2 and it's slow for large date differences, but for a period of a few years and to be used in ad-hoc scripting it's quite handy.
And if you happen to have MySQl or similar installed there is a very quick option :
The last
tr
allows you to enter the dates in any order (MySQL would else render a '-'if the first date is earlier than the second)[1] The reason for generating a list of dates is that with that I can generate the names of the logfiles that are in this format: YYYYmmdd.log.gz. I could do that using an asterisk or $(ls), but this is way slower than just providing a list with strings.