I‘m aware of date +%u to get the day of the week for today.
I‘d like to get that integer for any arbitrary date i input - if possible in the format I choose (e.g. %YYmmdd)
ok, found it finally:
date -j -f %Y%m%d +%u 20200910
this is, because date on macOS doesn't take a switch for putting in custom date (fyi for those folks, how try to make -v work, like me^^)
in addition, -f affects only input format (it's literally the second word in the man page, but I managed to overlook more than once)
-j is needed to use -f without setting the date.
hope this will spare someone time in the future ;)
edit:
it seems to be important, to specify input format before output format (see comment from #chepner below)
(also be careful with quotes)
$ date +%u -d "2020-09-10"
4
Related
I need to find today's date and then subtract a year and format that date into the YYYY-MM-dd format.
I am able to accomplish this with a script I wrote, but apparently it is only compatible with bash. I need it to be compatible with AIX.
lastYear=`date +'%Y-%m-%d' -d 'last year'`
searchDate="$lastYear 00.00.00";
echo "Retrieving data start from $searchDate"
myquery="myquery >= '$searchDate'"
The result when run on an AIX machine is that it only passes the "00:00:00" part of the $searchDate, the date does not prefix before the time as I hoped. What is the safest way to write this for the most compatibility across Linux/Unix variations?
Thank you!
Why make it so complicated?
#!/bin/ksh
typeset -i year=$( date +%Y )
(( year -= 1 ))
typeset rest=$( date +%m-%d )
echo "${year}-${rest}"
This should work in any shell. If you use sh replace the
$( ... )
with back tics
` ... `
But for bash and ksh I use $( ... ) -- just personal preference.
Checkout Updated Section Below
Original Answer
Try this. It uses the -v flag to display the result of adjusting the current date by negative one year -1y
searchDate=$(date -v-1y +'%Y-%m-%d')
echo "Retrieving data start from $searchDate"
myquery="myquery >= '$searchDate'"
Here is the output:
Retrieving data start from 2017-06-21
Note: I did try to run the lines you provided above in a script file with a bash shebang, but ran into an illegal time format error and the output was 00:00:00. The script I provided above runs cleanly on my unix system.
Hope this helps. Good luck!
Updated Section
Visit ShellCheck.net
It's a nice resource for testing code compatibility between sh, bash, dash, and ksh(AIX's default) shells.
Identifying the Actual Issue
When I entered your code, it clearly identified syntax that is considered legacy and suggested how to fix it, and gave this link with an example and a great explanation. Here's the output:
lastYear=`date +'%Y-%m-%d' -d 'last year'`
^__Use $(..) instead of legacy `..`.
So, it looks like you might be able to use the code you wrote, by making one small change:
lastYear=$(date +'%Y-%m-%d' -d 'last year')
Note: This question already has an accepted answer, but I wanted to share this resource, because it may help others trouble-shoot shell compatibility issues like this in the future.
I am trying to get the last time the date a file was modified. I used a variable for date and a variable for time.
This will get the date and time but I want to use -r using the date command to make a reflection of when the date was last modified. Just not sure how I go about using it in my variables.
How would I go about doing this?
Here are my variables:
DATE="$(date +'%m/%d/%Y')"
TIME="$(date +'%H:%M')"
I tried putting the -r after and before the time and date.
Though people might tell you, you should not parse the output of ls, simply that can easily break if your file name contains tabs, spaces, line breaks, your user decides to simply specify a different set of ls options, the ls version you find is not behaving like you expected...
Use stat instead:
stat -c '%Y'
will give you the seconds since epoch.
Try
date -d "#$(stat -c '%Y' $myfile)" "+%m/%d/%Y"
to get the date, and read through man date to get the time in the format you want to, replacing '%F' in the command line above:
date -d "#$(stat -c '%Y' $myfile)" "+%H:%M"
EDIT: used your formats.
EDIT2: I really don't think your date format is wise, because it's just so ambiguous for anyone not from the US, and also it's not easily sortable. But it's a cultural thing, so this is more of a hint: If you want to make your usable for people from abroad, either use Year-month-day as format, or get the current locale's setting to format dates.
I think you are looking for
ls -lt myfile.txt
Here in 6th column you will see when file was modified.
Or you could use stat myfile.txt to check the modified time of a file.
I know this is a very old question, but, for the sake of completeness, I'm including an additional answer here.
The original question does not specify the specific operating system. stat differs significantly from SysV-inspired Unixes (e.g. Linux) and BSD-inspired ones (e.g. Free/Open/NetBSD, macOS/Darwin).
Under macOS Big Sur (11.5), you can get the date of a file with a single stat command:
stat -t '%m/%d/%Y %H:%M' -f "%Sm" myfile.txt
will output
04/10/2021 23:22
for April 10, 2021.
You can easily put that in two commands, one for the date, another for the time, of course, to comply with the original question as formulated.
Use GNU stat.
mtime=$(stat --format=%y filename)
sample code :
modified_time=`ls -lt core* | head -1 | awk '{print $6,$7,$8}'`
echo modified time = $modified_time
I am trying to convert the last modified time for a file in seconds with the help of below command on aix box
t2=`date +'%s' -d "$modified_time"`
echo t2 = $t2
Note : the code i have posted is working on cygwin on bash. However its giving error on AIX ( ksh ).
I am getting below error :
egdev04{stc}[/home/stc]% t2=`date +'%s' -d "$modified_time"`
Invalid character in date/time specification.
Usage: date [-u] [+Field Descriptors]
Could someone please let me know what part of the code is wrong and suggest what needs to be used instead.
Unfortunately, date(1) is really poorly covered by standards, especially on dated systems, such as AIX (no pun intended).
Even on modern GNU/Linux vs BSD systems, there are different keys to achieve the behavior that you try to invoke:
GNU date has one key:
-d, --date=STRING
display time described by STRING, not 'now'
BSD date would use two keys and special invocation:
date [-jnRu] -f input_fmt new_date [+output_fmt]
-j Do not try to set the date. This allows you to use the -f flag
in addition to the + option to convert one date format to
another.
-f Use input_fmt as the format string to parse the new_date provided
rather than using the default [[[[[cc]yy]mm]dd]HH]MM[.ss] format.
Parsing is done using strptime(3).
AIX doesn't seem to include either one of these facilities. So, ultimately, if you really need that you'll have to execute a micro-script in some scripting language, such as Perl/Ruby/Python/etc.
Going a step backwards, parsing results of ls(1) is always a very bad idea, as they tend to vary wildly based on particular OS implementation, locale, output format, "human-readable" defaults, etc. If you really just want to get some file modification time, why don't you use stat(1)? May be it's available on AIX? Something like
stat -c '%Y' "$file"
seems to solve your task.
I have a shell script where I ask the system to return the year, 660days ago. On my Mac, I use this:
date -j -v-660d +"%Y"
If run today, that would return 2011.
I'm moving the script to an Ubuntu machine, and I receive an error, stating that the -j and -v options are invalid.
I've looked at the man page, looking for equivalent options, but haven't been able to find a solution.
Any help is appreciated.
This should work:
$ date -d '660 days ago' +%Y
2011
Sometimes, there are more than one version of utilities like date. Oftentimes, the version shipped on Linux is not the same as the version shipped on BSD or macOS.
I found the man page for date on FreeBSD, and it says this:
-j Do not try to set the date. This allows you to use the -f flag
in addition to the + option to convert one date format to an-
other. Note that any date or time components unspecified by the
-f format string take their values from the current time.
-v [+|-]val[y|m|w|d|H|M|S]
Adjust (i.e., take the current date and display the result of the
adjustment; not actually set the date) the second, minute, hour,
month day, week day, month or year according to val. If val is
preceded with a plus or minus sign, the date is adjusted forwards
or backwards according to the remaining string, otherwise the
relevant part of the date is set. The date can be adjusted as
many times as required using these flags. Flags are processed in
the order given.
For the GNU version of date shipped on Linux, typically, the only way to set the date is to pass -s. So we don't need the -j flag. The GNU version of date has -d display the date describe by a passed string.
In your case, you want:
$ date -d '660 days ago' +%Y
2021
I have a string with a custom date format written in Japanese: 2013年1月8日 20時19分. With osx's date command, I can convert this to some other format with the following command:
timestamp="2013年1月8日 20時19分"
date -j -f "%Y年%m月%d日 %H時%M分" "$timestamp" +"%F %R"
While searching I found this question helpful, but it ultimately did not help when it came to gnu date. The command gdate -d "2013年1月8日 20時19分" +"%F %R" fails saying that it does not understand the date format. The -d flag allows some simple formats, but how I can apply a more radical custom format and convert the date? Am I stuck with parsing the string myself with string manipulation in shell?
Any help would be greatly appreciated.
You probably will have to tinker with some environment variables (ex: TZ, LC_ALL, etc).
See this page showing you most of the common environnement variables, and their meanings
To try some: you can force the value to change just for the duration of the following command by putting them on the same line, before the command itself:
TZ=.... LC_LANG=..... date -d .......
will invoke date -d .... with the 2 environment variables TZ and LC_LANG set to a temporary value.
Some interresting pointers (I can't right now tell if there is a program that will take as input any locale's date and translate that to the relevant Epoch or Unix Timestamp... BUt there seems to be hope following that (looking quite standard) trail of online docs:
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/date.html
http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_02
which talks, amongst many other, about:
LC_TIME
This variable shall determine the locale category for date and time formatting information. It affects the behavior of the time functions in strftime(). Additional semantics of this variable, if any, are implementation-defined.
Which points to: http://pubs.opengroup.org/onlinepubs/9699919799/functions/getdate.html
which says in the middle:
The match between the template and input specification performed by getdate() shall be case-insensitive.
The month and weekday names can consist of any combination of upper and lowercase letters. The process can request that the input date or time specification be in a specific language by setting the LC_TIME category (see setlocale ).
and points to: http://pubs.opengroup.org/onlinepubs/9699919799/functions/setlocale.html
... I wish you an happy reading ! Let us know what you find!
I finally figured this out with the aid of the coreutils mailing list. However, the example they give there uses perl. They specifically rely on the POSIX::strptime module, which does not come with a standard installation of perl. Therefore, I solved this with python, which has the time module. This module should be available in most installations of python2 and python3.
Here's how to use it programmatically:
Python solution:
$ timestamp='2013年1月8日 20時19分'
$ time_format='%Y年%m月%d日 %H時%M分'
$ gdate -u -R -d "$(python -c 'import sys; from time import strptime; t=strptime(sys.argv[-1],"'$time_format'"); print("%d-%d-%d %d:%d"%(t.tm_year,t.tm_mon,t.tm_mday,t.tm_hour,t.tm_min))' $timestamp)"
Tue, 08 Jan 2013 20:19:00 +0000
This works with both python2 and python3. You can substitute any timestamp and format as you like.
Perl solution
To document the answer given to me on coreutils, the perl solution is this (requires POSIX::strptime)
$ gdate -u -R -d "$(perl -MPOSIX::strptime -le 'my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = POSIX::strptime("$ARGV[0]","%Y年%m月%d日 %H時%M分");$year+=1900;$mon+=1;printf("%04d-%02d-%02d %0d:%02d\n",$year,$mon,$mday,$hour,$min);' "2013年1月8日 20時19分")"