Skip to content

Instantly share code, notes, and snippets.

@aks
Created May 15, 2015 23:08
Show Gist options
  • Save aks/3375b24ac28282959bcf to your computer and use it in GitHub Desktop.
Save aks/3375b24ac28282959bcf to your computer and use it in GitHub Desktop.
Date Parser in Bash
# date_parse_str DATESTRING
#
# parse the DATESTRING. It can be in one of several formats: YYYY-MM-DD,
# YYYY.MM.DD, YYYY/MM/DD, YYYY MM DD, DD MMM YYYY, MMM DD, YYYY, and DD/MM/YYYY
# (if EUROPEAN_DATES is set).
#
# Sets the variables: year, month, day --- unless there was a parser failure
date_parse_str() {
local date="${1:-`date +%F`}"
local euro_format=
weekday_name= tzone= timestr= year= month= day=
case "$date" in
*-*-*) date="${date//-/ }" ;; # replace '-' with blanks
*.*.*) date="${date//./ }" ; euro_format=1 ;; # replace '.' with blanks
*/*/*) date="${date//\// }" ;; # repace '/' with blanks
esac
# YYYY MM DD
if [[ "$date" =~ ([0-9]{4})\ ([ 0-9]{1,2})\ ([ 0-9]{1,2}) ]]; then # yyyy mm dd
date_parse_ymd ${BASH_REMATCH[1]} ${BASH_REMATCH[2]} ${BASH_REMATCH[3]}
# MMM DD, YYYY or MMMM DD, YYYY
elif [[ "$date" =~ ([[:alpha:]]+)\ +([0-9]{1,2}),?\ +([0-9]{4}) ]]; then
date_parse_mmmdy ${BASH_REMATCH[1]} ${BASH_REMATCH[2]} ${BASH_REMATCH[3]}
# DD MMM YYYY
elif [[ "$date" =~ ([0-9]{1,2})\ +([[:alpha:]]+)\ +([0-9]]{4}) ]]; then
date_parse_mmmdy ${BASH_REMATCH[2]} ${BASH_REMATCH[1]} ${BASH_REMATCH[3]}
# MM DD YYYY or DD MM YYYY
elif [[ "$date" =~ ([0-9]{1,2})\ ([ 0-9]{1,2})\ ([0-9]{4}) ]] ; then # mm dd yyyy or dd mm yyyy
if (( EUROPEAN_DATES || euro_format )) ; then
date_parse_dmy ${BASH_REMATCH[1]} ${BASH_REMATCH[2]} ${BASH_REMATCH[3]}
else
date_parse_mdy ${BASH_REMATCH[1]} ${BASH_REMATCH[2]} ${BASH_REMATCH[3]}
fi
# WDAY MMM DD HH:MM:SS TZONE YYYY
elif [[ "$date" =~ ([[:alpha:]]{2,9})\ ([[:alpha:]]{3,8})\ ([ 0-9]{2})\ ([0-9]{2}:[0-9]{2}:[0-9]{2})\ ([[:alnum:]]{3,9})\ ([0-9]{4}) ]] ; then
date_parse_mmmdy ${BASH_REMATCH[2]} ${BASH_REMATCH[3]} ${BASH_REMATCH[6]}
weekday_name=${BASH_REMATCH[1]} timestr="${BASH_REMATCH[4]}" tzone="${BASH_REMATCH[5]}"
else # failure -- leave no variables set
:
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment