Convert input string to date in shell script
67,158
Solution 1
The OS X version of date
uses the -f
option to parse a formatted date/time:
date -j -f '%Y%m%d' "$1" +'%Y%m%d'
The -j
option causes it to just print the time, not try to set the system clock. So the full script would be:
#!/bin/bash
echo "$1";
startd=$(date -j -f '%Y%m%d' "$1" +'%Y%m%d');
echo "$startd";
Here's a transcript:
$ ./testdate.sh 20151010
20151010
20151010
Solution 2
If you are trying to format date on OS X, you can try this:
date -j -f "%Y%m%d" "20151010"
I get the following output:
Sat Oct 10 17:27:28 CDT 2015
Related videos on Youtube
Author by
PUG
Updated on September 18, 2022Comments
-
PUG almost 2 years
My shell script:
#!/bin/bash echo "$1"; startd=$(date -d "$1" +"%Y%m%d"); echo "$startd";
My command:
sudo ./test.sh "20151010"
The output:
20151010 20150213
it printed todays date instead of printing the input date any idea?
-
vinc17 over 9 yearsI have no such problem with
date
under Linux. You may need to install the GNU Coreutils and usedate
from them. BTW, you do not needsudo
. -
Barmar over 9 yearsThe OS X version of
date
doesn't parse arbitrary date formats like the GNU version does.
-
-
PUG over 9 yearsit turns out developing these scripts on osx won't do for me than because production env is linux, And i want the linux version of scripts