to_epoch.sh #1

  • //
  • p4-sdp/
  • dev_rebrand/
  • Unsupported/
  • Samples/
  • bin/
  • to_epoch.sh
  • View
  • Commits
  • Open Download .zip Download (1 KB)
#!/usr/bin/env bash

set -e

# Usage: ./to_epoch.sh <YYYY/MM/DD|YYYY/MM/DD:HH:MM:SS> [TIMEZONE]

INPUT_STAMP="$1"
TARGET_TZ="${2:-UTC}"

if [ -z "$INPUT_STAMP" ]; then
    echo "Usage: $0 <YYYY/MM/DD|YYYY/MM/DD:HH:MM:SS> [TIMEZONE]"
    echo "Examples:"
    echo "  $0 2026/12/31"
    echo "  $0 2026/12/31:18:30:00"
    echo "  $0 2026/12/31:18:30:00 America/New_York"
    exit 1
fi

# Extract date and time parts
if [[ "$INPUT_STAMP" == *":"* ]]; then
    # Splits on the first colon separating the date from time
    DATE_PART="${INPUT_STAMP%%:*}"
    TIME_PART="${INPUT_STAMP#*:}"
else
    DATE_PART="$INPUT_STAMP"
    TIME_PART="23:59:59"
fi

DATETIME_STR="${DATE_PART} ${TIME_PART}"

# Detect GNU date vs BSD/macOS date
if date --version >/dev/null 2>&1; then
    # GNU date (Ubuntu, Rocky, SLES)
    EPOCH=$(TZ="$TARGET_TZ" date -d "$DATETIME_STR" +%s 2>/dev/null)
else
    # BSD / macOS date
    EPOCH=$(TZ="$TARGET_TZ" date -j -f "%Y/%m/%d %H:%M:%S" "$DATETIME_STR" +%s 2>/dev/null)
fi

if [ -z "$EPOCH" ]; then
    echo "Error: Failed to parse date string '$INPUT_STAMP'. Ensure format is YYYY/MM/DD or YYYY/MM/DD:HH:MM:SS." >&2
    exit 1
fi

echo "$EPOCH"
# Change User Description Committed
#1 33190 C. Thomas Tyler Added sample epoch time conversion that works on many platforms.

Requirements:
* Works on Ubuntu 20-26, Rocky 8-10, SLES 15, and BSD and Mac (at least modern Mac, e.g. Tahoe)
* Accepts a datetamp in the form of YYYY/MM/DD or YYYY/MM/DD:HH:MM:SS (if the hour/minute/second is omitted, it defaults to 23:59:59).
* Provide an optional way to specify time zone, with UTC as the default.

Key Highlights
* Cross-Platform Compatibility: GNU Linux uses date -d, while BSD/macOS uses date -j -f "%Y/%m/%d %H:%M:%S". The if date --version check handles the branch automatically without relying on uname.
* Flexible Input: Handles both YYYY/MM/DD and YYYY/MM/DD:HH:MM:SS by leveraging shell parameter expansion (${INPUT_STAMP%%:*} and ${INPUT_STAMP#*:}).
* Timezone Safety: Sets TZ="$TARGET_TZ" per execution without mutating the caller's global shell environment.