shithub: mc

ref: 33f429bcdd5beeed24a8650320e9d3a83ce2d6f5
dir: /lib/date/date.myr/

View raw version
use std
use "types.use"
use "zoneinfo.use"

pkg date =
	/* useful constructors */
	const utcnow	: (-> instant)
	const now	: (tz : byte[:] -> instant)
	const tozone	: (d : instant, zone : byte[:]	-> instant)
	const mkdate	: (tm : std.time, zone : byte[:]	-> instant)

	const localoff	: (tm : std.time -> diff)
	const tzoff	: (tzname : byte[:], tm : std.time	-> diff)
	const isleap	: (d : instant	-> bool)

	/* date differences */
	const add	: (d : instant, dt : diff	-> instant)
	const sub	: (d : instant, dt : diff	-> instant)
	const diff	: (a : instant, b : instant	-> diff)
	const duradd	: (d : instant, dt : duration	-> instant)
	const dursub	: (d : instant, dt : duration	-> instant)
;;

const Unix2Julian	= 719468
const Days400y	= 365*400 + 4*25 - 3
const Days4y	= 365*4 + 1

const utcnow = {
	-> mkdate(std.now(), "")
}

const now = {tz : byte[:]
	var tm

	tm = std.now()
	-> mkdate(tm, tz)
}

const tozone = {d, tz
	-> mkdate(d.actual, tz)
}

const mkdate = {tm, tz 
	var j, y, m, d
	var t, e
	var date
	var off

	date.actual = tm
	/* time zones */
	std.assert(tz.len <= date._tzbuf.len, "time zone name too long\n")
	off =_zoneinfo.findtzoff(tz, tm) 
	date.tzoff = off
	std.slcp(date._tzbuf[:tz.len], tz)
	date.tzname = date._tzbuf[:tz.len]
	tm += off castto(std.time)

	/* break up time */
	t = tm % (24*60*60*1_000_000)	/* time */
	e = tm / (24*60*60*1_000_000)	/* epoch days */


	/* microseconds, seconds, minutes, hours */
	date.us 	= (t % 1_000_000) castto(int)
	t /= 1_000_000
	date.s 	= (t % 60) castto(int)
	t /= 60
	date.m	= (t % 60) castto(int)
	t /= 60
	date.h  = t castto(int)

	/* weekday */
	date.wday = ((e + 4) % 7) castto(int)	/* the world started on Thursday */

	/*
	split up year, month, day.

	Implemented according to "Algorithm 199, conversions between calendar 
	date and Julian day number", Robert G. Tantzen, Air Force Missile Development
	Center, Holloman AFB, New Mex.

	Lots of magic. Yer a wizard, 'arry.
	*/
	j = e + Unix2Julian
	y = (4 * j - 1) / Days400y
	j = 4 * j - 1 - Days400y * y
	d = j / 4
	j = (4 * d + 3) / Days4y
	d = 4 * d + 3 - Days4y * j
	d = (d + 4) / 4 ;
	m = (5 * d - 3) / 153
	d = 5 * d - 3 - 153 * m
	d = (d + 5) / 5
	y = 100 * y + j
	if m < 10
		m += 3
	else
		m -= 9 
		y++
	;;
	date.year = y castto(int)
	date.mon = m castto(int)
	date.day = (d + 1) castto(int)
	-> date
}

const localoff = {tm
	-> _zoneinfo.findtzoff("local", tm)
}

const tzoff = {tz, tm
	-> _zoneinfo.findtzoff(tz, tm)
}

const isleap = {d
	-> d.year % 4 == 0 && (d.year % 100 != 0 || d.year % 400 == 0)
}

const add  = {d, dt
	-> mkdate(d.actual + (dt castto(std.time)), d.tzname)
}

const sub  = {d, dt
	-> mkdate(d.actual - (dt castto(std.time)), d.tzname)
}

const diff = {a, b
	-> (b.actual - a.actual) castto(diff)
}