Julia Date and Time

Julia provides powerful date and time processing capabilities through the Dates standard library.

Basic Types

Import Dates Module

using Dates

Date Type (Date)

# Create date
d = Date(2024, 12, 25)
println(d)  # 2024-12-25

# Parse from string
d = Date("2024-12-25")
println(d)

# Today
today_date = today()
println(today_date)

DateTime Type (Date and Time)

# Create datetime
dt = DateTime(2024, 12, 25, 10, 30, 45)
println(dt)  # 2024-12-25T10:30:45

# Including milliseconds
dt = DateTime(2024, 12, 25, 10, 30, 45, 123)
println(dt)  # 2024-12-25T10:30:45.123

# Current time
now_time = now()
println(now_time)

# UTC time
utc_time = now(UTC)
println(utc_time)

Time Type (Time)

# Create time
t = Time(10, 30, 45)
println(t)  # 10:30:45

# Including milliseconds, microseconds, nanoseconds
t = Time(10, 30, 45, 123, 456, 789)
println(t)

Getting Date Time Components

dt = DateTime(2024, 12, 25, 10, 30, 45)

# Year, month, day
println(year(dt))       # 2024
println(month(dt))      # 12
println(day(dt))        # 25

# Hour, minute, second
println(hour(dt))       # 10
println(minute(dt))     # 30
println(second(dt))     # 45
println(millisecond(dt)) # 0

# Day of week (1=Monday, 7=Sunday)
println(dayofweek(dt))  # 3 (Wednesday)

# Day of year
println(dayofyear(dt))  # 360

# Quarter
println(quarterofyear(dt))  # 4

# Week number
println(week(dt))       # 52

# Month name
println(monthname(dt))  # December
println(monthabbr(dt))  # Dec

# Day name
println(dayname(dt))    # Wednesday
println(dayabbr(dt))    # Wed

Date Time Formatting

Format Output

using Dates

dt = DateTime(2024, 12, 25, 10, 30, 45)

# Using Dates.format
println(Dates.format(dt, "yyyy-mm-dd"))          # 2024-12-25
println(Dates.format(dt, "yyyy/mm/dd HH:MM:SS")) # 2024/12/25 10:30:45
println(Dates.format(dt, "dd-mm-yyyy"))          # 25-12-2024

# Common format codes
# y    - Year
# m    - Month
# d    - Day
# H    - Hour (24-hour)
# M    - Minute
# S    - Second
# s    - Millisecond
# u    - Month abbreviation (Jan, Feb...)
# U    - Month full name (January, February...)
# e    - Day abbreviation (Mon, Tue...)
# E    - Day full name (Monday, Tuesday...)

Parse Date Time

# Parse string
dt = DateTime("2024-12-25 10:30:45", "yyyy-mm-dd HH:MM:SS")
println(dt)

# Parse date
d = Date("25/12/2024", "dd/mm/yyyy")
println(d)

# Using DateFormat (more efficient)
df = DateFormat("yyyy-mm-dd HH:MM:SS")
dt1 = DateTime("2024-12-25 10:30:45", df)
dt2 = DateTime("2024-12-26 11:45:30", df)

# ISO format
dt = DateTime("2024-12-25T10:30:45")

Date Time Arithmetic

Time Intervals (Period)

# Period types
println(Year(1))
println(Month(2))
println(Week(3))
println(Day(4))
println(Hour(5))
println(Minute(6))
println(Second(7))
println(Millisecond(8))

# Combine Periods
period = Year(1) + Month(2) + Day(3)
println(period)

Addition and Subtraction

d = Date(2024, 1, 15)

# Addition
println(d + Day(10))       # 2024-01-25
println(d + Month(1))      # 2024-02-15
println(d + Year(1))       # 2025-01-15
println(d + Week(2))       # 2024-01-29

# Subtraction
println(d - Day(5))        # 2024-01-10
println(d - Month(2))      # 2023-11-15

# Combination
println(d + Year(1) + Month(2) + Day(3))

# For DateTime
dt = DateTime(2024, 1, 15, 10, 30)
println(dt + Hour(5))      # 2024-01-15T15:30:00
println(dt + Minute(45))   # 2024-01-15T11:15:00

Date Difference

d1 = Date(2024, 1, 1)
d2 = Date(2024, 12, 31)

# Calculate difference
diff = d2 - d1
println(diff)           # 365 days
println(diff.value)     # 365

# Convert to other units
dt1 = DateTime(2024, 1, 1, 0, 0)
dt2 = DateTime(2024, 1, 2, 12, 30)
diff = dt2 - dt1

println(Dates.value(diff))  # Milliseconds
println(diff / Hour(1))     # Hours
println(diff / Minute(1))   # Minutes

Date Ranges

# Date range
dates = Date(2024, 1, 1):Day(1):Date(2024, 1, 10)
for d in dates
    println(d)
end

# Weekly
weeks = Date(2024, 1, 1):Week(1):Date(2024, 3, 1)
println(collect(weeks))

# Monthly
months = Date(2024, 1, 1):Month(1):Date(2024, 12, 1)
for m in months
    println(monthname(m))
end

# Count days in range
println(length(Date(2024, 1, 1):Day(1):Date(2024, 12, 31)))  # 366 (leap year)

Comparing Dates

d1 = Date(2024, 1, 1)
d2 = Date(2024, 12, 31)

println(d1 < d2)   # true
println(d1 > d2)   # false
println(d1 == d2)  # false
println(d1 <= d2)  # true

# Compare datetimes
dt1 = DateTime(2024, 1, 1, 10, 0)
dt2 = DateTime(2024, 1, 1, 15, 0)
println(dt1 < dt2)  # true

Rounding Date Time

dt = DateTime(2024, 3, 15, 14, 35, 22)

# Round down (floor)
println(floor(dt, Hour))    # 2024-03-15T14:00:00
println(floor(dt, Day))     # 2024-03-15T00:00:00
println(floor(dt, Month))   # 2024-03-01T00:00:00

# Round up (ceil)
println(ceil(dt, Hour))     # 2024-03-15T15:00:00
println(ceil(dt, Day))      # 2024-03-16T00:00:00

# Round to nearest
println(round(dt, Hour))    # 2024-03-15T15:00:00

Time Zone Handling

using Dates
using TimeZones  # Needs installation

# Create timezone-aware time
tz = TimeZone("Asia/Shanghai")
zdt = ZonedDateTime(2024, 12, 25, 10, 30, tz)
println(zdt)

# Timezone conversion
utc = TimeZone("UTC")
zdt_utc = astimezone(zdt, utc)
println(zdt_utc)

# Local timezone
local_tz = localzone()
println(local_tz)

Unix Timestamp

# DateTime to timestamp
dt = DateTime(2024, 12, 25, 10, 30, 45)
timestamp = datetime2unix(dt)
println(timestamp)  # Seconds

# Timestamp to DateTime
dt = unix2datetime(timestamp)
println(dt)

# Millisecond timestamp
timestamp_ms = Dates.value(dt)  # Milliseconds since year 1

Practical Examples

Calculate Age

function calculate_age(birthdate::Date)
    today_d = today()
    age = year(today_d) - year(birthdate)
    
    # Check if birthday has passed
    if (month(today_d), day(today_d)) < (month(birthdate), day(birthdate))
        age -= 1
    end
    
    return age
end

birthday = Date(1990, 5, 15)
println("Age: $(calculate_age(birthday)) years old")

Working Days Calculation

function is_weekday(d::Date)
    return dayofweek(d) <= 5  # 1-5 is Monday to Friday
end

function add_workdays(start_date::Date, n::Int)
    current = start_date
    days_added = 0
    
    while days_added < n
        current += Day(1)
        if is_weekday(current)
            days_added += 1
        end
    end
    
    return current
end

start = Date(2024, 1, 15)
println("10 working days later: $(add_workdays(start, 10))")

Relative Date Formatting

function format_relative(dt::DateTime)
    diff = now() - dt
    seconds = Dates.value(diff) / 1000
    
    if seconds < 60
        return "just now"
    elseif seconds < 3600
        return "$(Int(floor(seconds / 60))) minutes ago"
    elseif seconds < 86400
        return "$(Int(floor(seconds / 3600))) hours ago"
    else
        return "$(Int(floor(seconds / 86400))) days ago"
    end
end

past = now() - Hour(2)
println(format_relative(past))  # "2 hours ago"

Calendar Generation

function print_calendar(year::Int, month::Int)
    first_day = Date(year, month, 1)
    last_day = lastdayofmonth(first_day)
    
    println("\n  $(monthname(first_day)) $year")
    println(" Mo Tu We Th Fr Sa Su")
    
    # Print spaces for first week
    first_dow = dayofweek(first_day)
    print("   " ^ (first_dow - 1))
    
    for d in day(first_day):day(last_day)
        print(lpad(d, 3))
        if dayofweek(Date(year, month, d)) == 7
            println()
        end
    end
    println()
end

print_calendar(2024, 1)

Date Constants

# Month constants
println(January)   # 1
println(December)  # 12

# Day constants
println(Monday)    # 1
println(Sunday)    # 7

# Create date using month name
d = Date(2024, December, 25)

Performance Tips

# 1. Pre-compile DateFormat
const MY_FORMAT = DateFormat("yyyy-mm-dd HH:MM:SS")

# Efficient parsing of multiple dates
dates_str = ["2024-01-01 10:00:00", "2024-01-02 11:00:00"]
dates = [DateTime(s, MY_FORMAT) for s in dates_str]

# 2. Avoid creating Date/DateTime in loops
# Bad
for i in 1:1000
    d = Date(2024, 1, 1) + Day(i)
end

# Good
start = Date(2024, 1, 1)
for i in 1:1000
    d = start + Day(i)
end

Next Steps

After learning date and time, continue with: