Julia 日期和时间
Julia 提供了强大的日期和时间处理功能,通过 Dates 标准库实现。
基础类型
导入 Dates 模块
julia
using DatesDate 类型(日期)
julia
# 创建日期
d = Date(2024, 12, 25)
println(d) # 2024-12-25
# 从字符串解析
d = Date("2024-12-25")
println(d)
# 今天
today_date = today()
println(today_date)DateTime 类型(日期时间)
julia
# 创建日期时间
dt = DateTime(2024, 12, 25, 10, 30, 45)
println(dt) # 2024-12-25T10:30:45
# 包含毫秒
dt = DateTime(2024, 12, 25, 10, 30, 45, 123)
println(dt) # 2024-12-25T10:30:45.123
# 当前时间
now_time = now()
println(now_time)
# UTC 时间
utc_time = now(UTC)
println(utc_time)Time 类型(时间)
julia
# 创建时间
t = Time(10, 30, 45)
println(t) # 10:30:45
# 包含毫秒、微秒、纳秒
t = Time(10, 30, 45, 123, 456, 789)
println(t)获取日期时间组件
julia
dt = DateTime(2024, 12, 25, 10, 30, 45)
# 年月日
println(year(dt)) # 2024
println(month(dt)) # 12
println(day(dt)) # 25
# 时分秒
println(hour(dt)) # 10
println(minute(dt)) # 30
println(second(dt)) # 45
println(millisecond(dt)) # 0
# 星期几(1=周一,7=周日)
println(dayofweek(dt)) # 3(周三)
# 一年中的第几天
println(dayofyear(dt)) # 360
# 季度
println(quarterofyear(dt)) # 4
# 周数
println(week(dt)) # 52
# 月份名称
println(monthname(dt)) # December
println(monthabbr(dt)) # Dec
# 星期名称
println(dayname(dt)) # Wednesday
println(dayabbr(dt)) # Wed日期时间格式化
格式化输出
julia
using Dates
dt = DateTime(2024, 12, 25, 10, 30, 45)
# 使用 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
# 常用格式码
# y - 年
# m - 月
# d - 日
# H - 小时(24小时制)
# M - 分钟
# S - 秒
# s - 毫秒
# u - 月份缩写(Jan, Feb...)
# U - 月份全名(January, February...)
# e - 星期缩写(Mon, Tue...)
# E - 星期全名(Monday, Tuesday...)解析日期时间
julia
# 解析字符串
dt = DateTime("2024-12-25 10:30:45", "yyyy-mm-dd HH:MM:SS")
println(dt)
# 解析日期
d = Date("25/12/2024", "dd/mm/yyyy")
println(d)
# 使用 DateFormat(更高效)
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 格式
dt = DateTime("2024-12-25T10:30:45")日期时间运算
时间间隔(Period)
julia
# Period 类型
println(Year(1))
println(Month(2))
println(Week(3))
println(Day(4))
println(Hour(5))
println(Minute(6))
println(Second(7))
println(Millisecond(8))
# 组合 Period
period = Year(1) + Month(2) + Day(3)
println(period)加减运算
julia
d = Date(2024, 1, 15)
# 加法
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
# 减法
println(d - Day(5)) # 2024-01-10
println(d - Month(2)) # 2023-11-15
# 组合
println(d + Year(1) + Month(2) + Day(3))
# 对 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日期差值
julia
d1 = Date(2024, 1, 1)
d2 = Date(2024, 12, 31)
# 计算差值
diff = d2 - d1
println(diff) # 365 days
println(diff.value) # 365
# 转换为其他单位
dt1 = DateTime(2024, 1, 1, 0, 0)
dt2 = DateTime(2024, 1, 2, 12, 30)
diff = dt2 - dt1
println(Dates.value(diff)) # 毫秒数
println(diff / Hour(1)) # 小时数
println(diff / Minute(1)) # 分钟数日期范围
julia
# 日期范围
dates = Date(2024, 1, 1):Day(1):Date(2024, 1, 10)
for d in dates
println(d)
end
# 每周
weeks = Date(2024, 1, 1):Week(1):Date(2024, 3, 1)
println(collect(weeks))
# 每月
months = Date(2024, 1, 1):Month(1):Date(2024, 12, 1)
for m in months
println(monthname(m))
end
# 计算范围内的天数
println(length(Date(2024, 1, 1):Day(1):Date(2024, 12, 31))) # 366(闰年)比较日期
julia
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
# 比较日期时间
dt1 = DateTime(2024, 1, 1, 10, 0)
dt2 = DateTime(2024, 1, 1, 15, 0)
println(dt1 < dt2) # true舍入日期时间
julia
dt = DateTime(2024, 3, 15, 14, 35, 22)
# 向下舍入(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
# 向上舍入(ceil)
println(ceil(dt, Hour)) # 2024-03-15T15:00:00
println(ceil(dt, Day)) # 2024-03-16T00:00:00
# 四舍五入(round)
println(round(dt, Hour)) # 2024-03-15T15:00:00时区处理
julia
using Dates
using TimeZones # 需要安装
# 创建带时区的时间
tz = TimeZone("Asia/Shanghai")
zdt = ZonedDateTime(2024, 12, 25, 10, 30, tz)
println(zdt)
# 时区转换
utc = TimeZone("UTC")
zdt_utc = astimezone(zdt, utc)
println(zdt_utc)
# 本地时区
local_tz = localzone()
println(local_tz)Unix 时间戳
julia
# DateTime 转时间戳
dt = DateTime(2024, 12, 25, 10, 30, 45)
timestamp = datetime2unix(dt)
println(timestamp) # 秒数
# 时间戳转 DateTime
dt = unix2datetime(timestamp)
println(dt)
# 毫秒时间戳
timestamp_ms = Dates.value(dt) # 从公元1年起的毫秒实用示例
计算年龄
julia
function calculate_age(birthdate::Date)
today_d = today()
age = year(today_d) - year(birthdate)
# 检查是否已过生日
if (month(today_d), day(today_d)) < (month(birthdate), day(birthdate))
age -= 1
end
return age
end
birthday = Date(1990, 5, 15)
println("年龄: $(calculate_age(birthday))岁")工作日计算
julia
function is_weekday(d::Date)
return dayofweek(d) <= 5 # 1-5 是周一到周五
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个工作日后: $(add_workdays(start, 10))")日期格式化工具
julia
function format_relative(dt::DateTime)
diff = now() - dt
seconds = Dates.value(diff) / 1000
if seconds < 60
return "刚刚"
elseif seconds < 3600
return "$(Int(floor(seconds / 60)))分钟前"
elseif seconds < 86400
return "$(Int(floor(seconds / 3600)))小时前"
else
return "$(Int(floor(seconds / 86400)))天前"
end
end
past = now() - Hour(2)
println(format_relative(past)) # "2小时前"月历生成
julia
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")
# 打印第一周的空格
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)日期常量
julia
# 月份常量
println(January) # 1
println(December) # 12
# 星期常量
println(Monday) # 1
println(Sunday) # 7
# 使用月份名创建日期
d = Date(2024, December, 25)性能提示
julia
# 1. 预编译 DateFormat
const MY_FORMAT = DateFormat("yyyy-mm-dd HH:MM:SS")
# 高效解析多个日期
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. 避免在循环中创建 Date/DateTime
# 不好
for i in 1:1000
d = Date(2024, 1, 1) + Day(i)
end
# 好
start = Date(2024, 1, 1)
for i in 1:1000
d = start + Day(i)
end下一步
学习完日期和时间后,请继续学习: