Skip to content

Instantly share code, notes, and snippets.

@hirusha-adi
Created May 16, 2025 12:26
Show Gist options
  • Save hirusha-adi/b0532075323c80da91cfba90b0cf034f to your computer and use it in GitHub Desktop.
Save hirusha-adi/b0532075323c80da91cfba90b0cf034f to your computer and use it in GitHub Desktop.
Store date/time properly

ISO 8601 Format

Timezones are a headache to begin with. Weird formats in how we represent time are even worse than having to deal with timezones. In Sri Lanka (and most of the world), when it comes to storing or sending date/time values, we go with the ISO 8601 format.

It basically avoids confusion compared to what the Americans use, as it’s more logical. We write everything in descending order. Otherwise, something like 01/02/03 could be Jan 2 or Feb 1 - and nobody would know. Sticking with ISO 8601 fixes this.

It stores your date/time like this. Note that the letter T separates the date and time:

YYYY-MM-DDTHH\:MM\:SS

With an offset - for example, to offset to IST (UTC+5:30), it would look like this:

YYYY-MM-DDTHH\:MM\:SS+05:30

🐍 Python Example

from datetime import datetime, timezone, timedelta

# Define Sri Lanka Standard Time (UTC+5:30)
# You can adjust the offset or use timezone.utc for UTC time
SL_OFFSET = timedelta(hours=5, minutes=30)
SL_TZ = timezone(SL_OFFSET)

def get_current_datetime_iso(tz=SL_TZ):
    """
    Returns the current datetime in ISO 8601 format for the specified timezone.
    """
    now = datetime.now(tz)
    return now.isoformat()

def format_custom_datetime_iso(year, month, day, hour=0, minute=0, second=0, tz=SL_TZ):
    """
    Returns a formatted ISO 8601 datetime string for a given date and time in a specified timezone.
    """
    custom_dt = datetime(year, month, day, hour, minute, second, tzinfo=tz)
    return custom_dt.isoformat()

def parse_iso8601_string(iso_str):
    """
    Parses an ISO 8601 formatted string back into a datetime object.
    """
    try:
        parsed_dt = datetime.fromisoformat(iso_str)
        return parsed_dt
    except ValueError as e:
        print("Invalid ISO 8601 string:", iso_str)
        print("Error:", e)
        return None

if __name__ == "__main__":
    print("=== πŸ“… ISO 8601 Date-Time in Python ===\n")

    # 1. Current time in SL timezone
    now_iso = get_current_datetime_iso()
    print("[Current Time in Sri Lanka]:")
    print(now_iso, "\n")

    # 2. Custom date: Sinhala & Tamil New Year 2025
    avurudu_iso = format_custom_datetime_iso(2025, 4, 13, 6, 30)
    print("[Avurudu 2025 - Custom Time]:")
    print(avurudu_iso, "\n")

    # 3. Parse ISO string back to datetime
    parsed = parse_iso8601_string(avurudu_iso)
    print("[Parsed Back to datetime object]:")
    print(parsed, "\n")

    # 4. UTC example
    utc_now = get_current_datetime_iso(timezone.utc)
    print("[Current Time in UTC]:")
    print(utc_now, "\n")

πŸ’» JavaScript Example

// Define Sri Lanka timezone offset manually (+05:30 = 330 minutes)
const SRI_LANKA_OFFSET_MINUTES = 330;

/**
 * Get current UTC time in ISO 8601
 */
function getCurrentUTC() {
  return new Date().toISOString();
}

/**
 * Get current time in Sri Lanka in ISO 8601 format
 * Adjusts manually from UTC
 */
function getCurrentSriLankaTimeISO() {
  const now = new Date();
  const utcTime = now.getTime() + now.getTimezoneOffset() * 60000;
  const slTime = new Date(utcTime + SRI_LANKA_OFFSET_MINUTES * 60000);
  return slTime.toISOString();
}

/**
 * Format a custom date/time (year, month, day, hour, minute) to ISO 8601 with SL offset
 */
function formatCustomDateISO(year, month, day, hour = 0, minute = 0, second = 0) {
  const date = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
  const slTime = new Date(date.getTime() + SRI_LANKA_OFFSET_MINUTES * 60000);
  return slTime.toISOString();
}

/**
 * Parse an ISO 8601 string back to a Date object
 */
function parseISO8601(isoString) {
  return new Date(isoString);
}

// === Usage ===
console.log("πŸ“… Current UTC:", getCurrentUTC());
console.log("πŸ‡±πŸ‡° Current Sri Lanka Time:", getCurrentSriLankaTimeISO());
console.log("πŸŽ‰ Avurudu 2025:", formatCustomDateISO(2025, 4, 13, 6, 30));
console.log("πŸ” Parsed Back:", parseISO8601("2025-04-13T06:30:00.000Z"));

Summary

  • Format is as follows: YYYY-MM-DDTHH:MM:SS+05:30
  • Python: datetime.now(timezone(...)).isoformat()
  • Javascript: new Date().toISOString() (but watch out for timezones)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment