Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active June 27, 2017 03:05
Show Gist options
  • Save magnetikonline/a4a90efcc25aa3bdb08bd961bca9a4f6 to your computer and use it in GitHub Desktop.
Save magnetikonline/a4a90efcc25aa3bdb08bd961bca9a4f6 to your computer and use it in GitHub Desktop.
Mac OS X - BSD date, converting UTC time to local time.

Mac OS X BSD date, convert UTC time to local time

  • Take a given UTC time and convert to a local time string in CCYYMMDDhhmm.SS format.
  • Offset the given time by minus 20 seconds (the -20S argument to -v).
date \
	-jf "%Y-%m-%dT%H:%M:%S %z" \
	-v -20S \
	"2016-04-11T03:26:02 +0000" \
	"+%Y%m%d%H%M.%S"

This output can then be pumped into something like touch:

dateTouch=$(
	date \
		-jf "%Y-%m-%dT%H:%M:%S %z" \
		-v -20S \
		"2016-04-11T03:26:02 +0000" \
		"+%Y%m%d%H%M.%S"
)

touch -t "$dateTouch" /path/to/my/file

Or as a Linux/OSX compatible Bash function for:

  • Taking a UTC date in YYYY-MM-DDTHH:MM:SS format and a positive/negative seconds offset.
  • Return a CCYYMMDDhhmm.SS format date in local time.
function getUTCDateSecondOffset {

	# Linux or BSD date?
	set +e
	date -v 0S >/dev/null 2>&1
	retVal=$?
	set -e

	if [[ $retVal -eq 0 ]]; then
		# BSD date
		date \
			-jf "%Y-%m-%dT%H:%M:%S %z" \
			-v "${2}S" \
			"${1} +0000" \
			"+%Y%m%d%H%M.%S"

	else
		# Linux date
		date --date "${1} +0000 ${2} seconds" "+%Y%m%d%H%M.%S"
	fi
}

getUTCDateSecondOffset "2016-04-11T03:26:02" "-20"
# 201604111325.42

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment