Plan 9 from Bell Labs’s /usr/web/sources/contrib/anothy/src/cmd/datefmt.b

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


implement Datefmt;

include "sys.m";
	sys: Sys;

include "draw.m";
include "daytime.m";
	daytime: Daytime;
include "arg.m";
	arg: Arg;

Datefmt: module
{
	init: fn(ctxt: ref Draw->Context, argv: list of string);
};

usage()
{
	sys->fprint(sys->fildes(2), "usage: %s [-t seconds] format", arg->progname());
}

init(nil: ref Draw->Context, argv: list of string)
{
	sys = load Sys Sys->PATH;
	daytime = load Daytime Daytime->PATH;
	arg = load Arg Arg->PATH;

	now := daytime->now();

	arg->init(argv);
	while((opt := arg->opt()) != 0)
		case opt {
		't' =>
			now = int arg->arg();
		* =>
			usage();
		}
	argv = arg->argv();
	if (len argv != 1)
		usage();

	t := daytime->local(now);

	sys->print("%s", format_t(hd argv, t));
}

format_t(format: string, t: ref daytime->Tm): string
{
	outb: string;
	j: int;
	for (i := 0; i < len format; i++) {
		if(format[i] != '%')
			outb=outb+sys->sprint("%c", format[i]);
		else case format[++i] {
#	There's a lot of these. I've started with what seems to be the most useful,
#	plus some unix common extensions, plus some new extensions.
#	C89:	aAbBc d       HIj  mM  p   S   U  wWxXyY Z%
#	here:	      dD  F   HIj  mMn prR StTu   w   yYzZ% α
#	OS X:	aAbBcCdDeEFgGhHIjklmMnOprRsStTuUvVwWxXyYzZ%+
#	There's no local-dependent stuff here, like OS X's E and O.

			# Fundamental elements.
			'S' =>
				outb+=sys->sprint("%.2d", t.sec);
			'M' =>
				outb+=sys->sprint("%.2d", t.min);
			'H' =>
				outb+=sys->sprint("%.2d", t.hour);
			'd' =>
				outb+=sys->sprint("%.2d", t.mday);
			'm' =>
				outb+=sys->sprint("%.2d", t.mon+1);
			'y' =>
				outb+=sys->sprint("%.2d", t.year%100);
			'Y' =>
				outb+=sys->sprint("%.4d", t.year+1900);
			'w' =>
				outb+=sys->sprint("%d", t.wday);
			'j' =>
				outb+=sys->sprint("%d", t.yday);
			'Z' =>
				outb+=sys->sprint("%s", t.zone);
			'z' =>
				outb+=sys->sprint("%d", t.tzoff);

			# Derived elements.
			'D' =>
				outb+=format_t("%m/%d/%y", t);
			'F' =>
				outb+=format_t("%Y-%m-%d", t);
			'I' =>
				j = t.hour%12;
				if (j == 0)
					j=12;
				outb+=sys->sprint("%.2d", j);
			'p' =>
				if (t.hour < 12)
					outb+="am";
				else
					outb+="pm";
			'R' =>
				outb+=format_t("%H:%M", t);
			'r' =>
				outb+=format_t("%I:%M:%S %p", t);
			'T' =>
				outb+=format_t("%H:%M:%S", t);
			'u' =>
				j =t.wday;
				if (j == 0)
					j = 7;
				outb+=sys->sprint("%d", j);

			# Non-standard additions.
			'α' =>
				outb+=format_t("%Y-%m-%dT%H:%M:%S", t);

			# Literals and other.
			'%' =>
				outb+="%";
			'n' =>
				outb+="\n";
			't' =>
				outb+="	";
			* =>
				;
		}
	}
	return outb;
}

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to webmaster@9p.io.