Skip to content

Instantly share code, notes, and snippets.

@tka
Created April 19, 2011 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tka/926976 to your computer and use it in GitHub Desktop.
Save tka/926976 to your computer and use it in GitHub Desktop.
#
# Returns a string which represents the time as dateTime defined by XML
# Schema:
#
# CCYY-MM-DDThh:mm:ssTZD
# CCYY-MM-DDThh:mm:ss.sssTZD
#
# where TZD is Z or [+-]hh:mm.
#
# If self is a UTC time, Z is used as TZD. [+-]hh:mm is used otherwise.
#
# +fractional_seconds+ specifies a number of digits of fractional seconds.
# Its default value is 0.
#
def xmlschema(fraction_digits=0)
sprintf('%d-%02d-%02dT%02d:%02d:%02d',
year, mon, day, hour, min, sec) +
if fraction_digits == 0
''
elsif fraction_digits <= 6
'.' + sprintf('%06d', usec)[0, fraction_digits]
else
'.' + sprintf('%06d', usec) + '0' * (fraction_digits - 6)
end +
if utc?
'Z'
else
off = utc_offset
sign = off < 0 ? '-' : '+'
sprintf('%s%02d:%02d', sign, *(off.abs / 60).divmod(60))
end
end
alias iso8601 xmlschema
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment