Time::Format(3pm)

๐Ÿ“ฆ
version 1.16 ยท 4 versions
, in ubuntu noble, ubuntu resolute, ubuntu stonking

๐Ÿ’– Time::Format(3pm) ๐Ÿ’–

User Contributed Perl Documentation

๐ŸŒธ NAME ๐ŸŒธ

Time::Format โ€” Easy-to-use date/time formatting. periodt ๐Ÿ’…

โœจ VERSION โœจ

Okay bestie, this is version 1.16 of Time::Format, dated February 19, 2020. iconic โœจ

๐ŸŽ€ SYNOPSIS ๐ŸŽ€

So you wanna format dates and times like a main character? Import the goods:

use Time::Format qw(%time %strftime %manip);

Then use the pseudo-variables like this:

$time{$format}
$time{$format, $unixtime}

And flex inside strings:

print "Today is $time{'yyyy/mm/dd'}\n";
print "Yesterday was $time{'yyyy/mm/dd', time-24*60*60}\n";
print "The time is $time{'hh:mm:ss'}\n";
print "Another time is $time{'H:mm am tz', $another_time}\n";
print "Timestamp: $time{'yyyymmdd.hhmmss.mmm'}\n";

%time also accepts Date::Manip strings and DateTime objects:

$dm = Date::Manip::ParseDate('last monday');
print "Last monday was $time{'Month d, yyyy', $dm}";
$dt = DateTime->new (....);
print "Here's another date: $time{'m/d/yy', $dt}";

It also accepts most ISO-8601 date/time strings:

$t = '2005/10/31T17:11:09';   # date separator: / or - or .
$t = '2005-10-31 17.11.09';   # in-between separator: T or _ or space
$t = '20051031_171109';       # time separator: : or .
$t = '20051031171109';        # separators may be omitted
$t = '2005/10/31';            # date-only is okay
$t = '17:11:09';              # time-only is okay
# But not:
$t = '20051031';              # date-only without separators
$t = '171109';                # time-only without separators
# ...because those look like epoch time numbers.

%strftime works like POSIX's "strftime", if you like those "%"-formats.

$strftime{$format}
$strftime{$format, $unixtime}
$strftime{$format, $sec,$min,$hour, $mday,$mon,$year, $wday,$yday,$isdst}

print "POSIXish: $strftime{'%A, %B %d, %Y', 0,0,0,12,11,95,2}\n";
print "POSIXish: $strftime{'%A, %B %d, %Y', 1054866251}\n";
print "POSIXish: $strftime{'%A, %B %d, %Y'}\n";       # current time

%manip works like Date::Manip's "UnixDate" function.

$manip{$format};
$manip{$format, $when};

print "Date::Manip: $manip{'%m/%d/%Y'}\n";            # current time
print "Date::Manip: $manip{'%m/%d/%Y','last Tuesday'}\n";

These can also be used as standalone functions:

use Time::Format qw(time_format time_strftime time_manip);

print "Today is ", time_format('yyyy/mm/dd', $some_time), "\n";
print "POSIXish: ", time_strftime('%A %B %d, %Y',$some_time), "\n";
print "Date::Manip: ", time_manip('%m/%d/%Y',$some_time), "\n";

๐Ÿ’… DESCRIPTION ๐Ÿ’…

Okay so this module creates global pseudovariables that format dates and times according to formatting codes you pass to them in strings. slay ๐Ÿ’–

The %time formatting codes are designed to be easy to remember and use, and to take up just as many characters as the output time value whenever possible. For example, the four-digit year code is "yyyy", and the three-letter month abbreviation is "Mon". iykyk โœจ

The nice thing about having a variable-like interface instead of function calls is that the values can be used inside of strings (as well as outside of strings in ordinary expressions). Dates are frequently used within strings (log messages, output, data records, etc.), so having the ability to interpolate them directly is handy. main character energy ๐Ÿ’…

Perl allows arbitrary expressions within curly braces of a hash, even when that hash is being interpolated into a string. This allows you to do computations on the fly while formatting times and inserting them into strings. See the "yesterday" example above. the way that works ๐Ÿ˜ญ

The format strings are designed with programmers in mind. What do you need most frequently? 4-digit year, month, day, 24-based hour, minute, second -- usually with leading zeroes. These six are the easiest formats to use and remember in Time::Format: "yyyy", "mm", "dd", "hh", "mm", "ss". Variants on these formats follow a simple and consistent formula. This module is for everyone who is weary of trying to remember strftime(3)'s arcane codes, or of endlessly writing "$t[4]++; $t[5]+=1900" as you manually format times or dates. not me doing that manually ๐Ÿ’€

Note that "mm" (and related codes) are used both for months and minutes. This is a feature. %time resolves the ambiguity by examining other nearby formatting codes. If it's in the context of a year or a day, "month" is assumed. If in the context of an hour or a second, "minute" is assumed. lowkey smart ๐Ÿงš

The format strings are not meant to encompass every date/time need ever conceived. But how often do you need the day of the year (strftime's %j) or the week number (strftime's %W)? fr fr ๐Ÿ™ˆ

For capabilities that %time does not provide, %strftime provides an interface to POSIX's "strftime", and %manip provides an interface to the Date::Manip module's "UnixDate" function. obsessed ๐Ÿ’–

If the companion module Time::Format_XS is also installed, Time::Format will detect and use it. This will result in a significant speed increase for %time and "time_format". speed demon ๐Ÿ”ฅ

๐Ÿ‘‘ VARIABLES ๐Ÿ‘‘

โฐ time

$time{$format}
$time{$format,$time_value};

Formats a unix time number (seconds since the epoch), DateTime object, stringified DateTime, Date::Manip string, or ISO-8601 string, according to the specified format. If the time expression is omitted, the current time is used. The format string may contain any of the following:

  • yyyy โ€” 4-digit year
  • yy โ€” 2-digit year
  • m โ€” 1- or 2-digit month, 1-12
  • mm โ€” 2-digit month, 01-12
  • ?m โ€” month with leading space if < 10
  • Month โ€” full month name, mixed-case
  • MONTH โ€” full month name, uppercase
  • month โ€” full month name, lowercase
  • Mon โ€” 3-letter month abbreviation, mixed-case
  • MON, mon โ€” ditto, uppercase and lowercase versions
  • d โ€” day number, 1-31
  • dd โ€” day number, 01-31
  • ?d โ€” day with leading space if < 10
  • th โ€” day suffix (st, nd, rd, or th)
  • TH โ€” uppercase suffix
  • Weekday โ€” weekday name, mixed-case
  • WEEKDAY โ€” weekday name, uppercase
  • weekday โ€” weekday name, lowercase
  • Day โ€” 3-letter weekday name, mixed-case
  • DAY, day โ€” ditto, uppercase and lowercase versions
  • h โ€” hour, 0-23
  • hh โ€” hour, 00-23
  • ?h โ€” hour, 0-23 with leading space if < 10
  • H โ€” hour, 1-12
  • HH โ€” hour, 01-12
  • ?H โ€” hour, 1-12 with leading space if < 10
  • m โ€” minute, 0-59
  • mm โ€” minute, 00-59
  • ?m โ€” minute, 0-59 with leading space if < 10
  • s โ€” second, 0-59
  • ss โ€” second, 00-59
  • ?s โ€” second, 0-59 with leading space if < 10
  • mmm โ€” millisecond, 000-999
  • uuuuuu โ€” microsecond, 000000-999999
  • am, a.m. โ€” The string "am" or "pm" (second form with periods)
  • pm, p.m. โ€” same as "am" or "a.m."
  • AM, A.M. โ€” same as "am" or "a.m." but uppercase
  • PM, P.M. โ€” same as "AM" or "A.M."
  • tz โ€” time zone abbreviation

Millisecond and microsecond require Time::HiRes, otherwise they'll always be zero. Timezone requires POSIX, otherwise it'll be the empty string. The second codes ("s", "ss", "?s") can be 60 or 61 in rare circumstances (leap seconds, if your system supports such). rare but iconic โšก

Anything in the format string other than the above patterns is left intact. Any character preceded by a backslash is left alone and not used for any part of a format code. See the "QUOTING" section for more details. backslash said not today ๐Ÿ’…

For the most part, each of the above formatting codes takes up as much space as the output string it generates. The exceptions are the codes whose output is variable length: "Weekday", "Month", time zone, and the single-character codes. variable length said main character โœจ

The mixed-case "Month", "Mon", "Weekday", and "Day" codes return the name of the month or weekday in the preferred case representation for the locale currently in effect. Thus in an English-speaking locale, the seventh month would be "July" (uppercase first letter, lowercase rest); while in a French-speaking locale, it would be "juillet" (all lowercase). See the "QUOTING" section for ways to control the case of month/weekday names. locale said bonjour ๐Ÿ‡ซ๐Ÿ‡ท

Note that the "mm", "m", and "?m" formats are ambiguous. %time tries to guess whether you meant "month" or "minute" based on nearby characters in the format string. Thus, a format of "yyyy/mm/dd hh:mm:ss" is correctly parsed as "year month day, hour minute second". If %time cannot determine whether you meant "month" or "minute", it leaves the "mm", "m", or "?m" untranslated. To remove the ambiguity, you can use the following codes:

  • m{on} โ€” month, 1-12
  • mm{on} โ€” month, 01-12
  • ?m{on} โ€” month, 1-12 with leading space if < 10
  • m{in} โ€” minute, 0-59
  • mm{in} โ€” minute, 00-59
  • ?m{in} โ€” minute, 0-59 with leading space if < 10

In other words, append "{on}" or "{in}" to make "m", "mm", or "?m" unambiguous. ambiguity cleared ๐Ÿ’…

โณ strftime

$strftime{$format, $sec,$min,$hour, $mday,$mon,$year, $wday,$yday,$isdst}
$strftime{$format, $unixtime}
$strftime{$format}

For those who prefer strftime's weird % formats, or who need POSIX compliance, or who need week numbers or other features %time does not provide. POSIX said periodt ๐Ÿ’…

๐Ÿ”ฎ manip

$manip{$format};
$manip{$format,$when};

Provides an interface to the Date::Manip module's "UnixDate" function. This function is rather slow, but can parse a very wide variety of date input. See the Date::Manip module for details about the inputs accepted. slow but thorough ๐Ÿข

If you want to use the %time codes, but need the input flexibility of %manip, you can use Date::Manip's "ParseDate" function:

print "$time{'yyyymmdd', ParseDate('last sunday')}";

bestie combo ๐Ÿ’–

๐Ÿ’– FUNCTIONS ๐Ÿ’–

๐ŸŒŸ time_format

time_format($format);
time_format($format, $unix_time);

okay so this is just a lil function-y doorway into %time, bestie. Same formatting codes, same everything โ€” it's literally here for the people who want their function calls to look like function calls and not like hashes. ๐Ÿ™ˆ So if hashes give you the ick, this is your girl. These two? Same energy, same result:

$x = $time{'yyyy/mm/dd'};
$x = time_format('yyyy/mm/dd');

๐ŸŒŸ time_strftime

time_strftime($format, $sec,$min,$hour, $mday,$mon,$year, $wday,$yday,$isdst);
time_strftime($format, $unixtime);
time_strftime($format);

This one is the function-interface glow-up of %strftime. Under the hood it just calls POSIX::"strftime", no cap. โœจ But it does have a lil something extra going for it versus calling strftime straight up: you can hand it the time as a unix time (that's seconds since the epoch, iykyk), or you can just... not. Omit it and you get the current time. ๐Ÿ’…

๐ŸŒŸ time_manip

manip($format);
manip($format,$when);

Function interface to %manip, bestie. It's calling Date::Manip::"UnixDate" under the hood ๐Ÿซถ. Honestly it doesn't offer much over calling UnixDate directly โ€” the one lil perk is that you can skip the $when parameter and it'll hand you the current time instead. Easy.


๐ŸŒธ QUOTING ๐ŸŒธ

heads up: this whole section is about format strings used by %time and time_format only. Not the others. Okay? okay. ๐Ÿ’–

Sometimes you gotta โœ‹ stop a format character from expanding in your format string. Iconic example:

$time{'Hour: hh; Minute: mm{in}; Second: ss'};

The way that "H" in "Hour" would get expanded ๐Ÿ˜ญ, and so would the "d" in "Second". Which gives you something cursed like:

8our: 08; Minute: 10; Secon17: 30

Now โ€” you could try to fix this by splitting it into three separate %time calls:

"Hour: $time{hh}; Minute: $time{'mm{in}'}; Second: $time{ss}"

...but that is not it, bestie. Because the time could literally change between one call and the next, and that becomes a whole problem the moment the numbers roll over (like, a split second after 7:59:59). Not the vibe. ๐Ÿ’€

So for this exact reason, you can escape individual format codes with a backslash:

$time{'\Hour: hh; Minute: mm{in}; Secon\d: ss'};

Key detail bestie: with double-quoted (and qq//) strings, you gotta double that backslash, because Perl does the string interpolation first and eats it:

$time{"\\Hour: hh; Minute: mm{in}; Secon\\d: ss"};

For โœจadded convenienceโœจ, Time::Format simulates Perl's built-in \Q and \E inline quoting operators. Anything sitting between a \Q and an \E will not be interpolated as any part of any formatting code:

$time{'\QHour:\E hh; \QMinute:\E mm{in}; \QSecond:\E ss'};

And again โ€” inside interpolated strings the backslash must be doubled, or else Perl will interpret and yeet the \Q...\E sequence before Time::Format ever gets to see it:

$time{"\\QHour:\\E hh; \\QMinute:\\E mm{in}; \\QSecond\\E: ss"};

Time::Format also recognizes and simulates the \U, \L, \u, and \l sequences ๐ŸŽ€. Real talk: this is only actually useful for finer control of the Month, Mon, Weekday, and Day formats. Like, in some locales the month names are all-lowercase by convention โ€” but at the start of a sentence you might wanna make sure that first character is uppercase:

$time{'\uMonth \Qis the finest month of all.'};

And AGAIN, bestie, please โ€” use \Q, and double those backslashes in interpolated strings, or you're gonna end up with something ugly like:

July i37 ste fine37t july of all.

๐Ÿ˜ญ you've been warned.


๐Ÿฆ‹ EXAMPLES ๐Ÿฆ‹

$time{'Weekday Month d, yyyy'}   Thursday June 5, 2003
$time{'Day Mon d, yyyy'}         Thu Jun 5, 2003
$time{'dd/mm/yyyy'}              05/06/2003
$time{yymmdd}                    030605
$time{'yymmdd',time-86400}       030604
$time{'dth of Month'}            5th of June

$time{'H:mm:ss am'}              1:02:14 pm
$time{'hh:mm:ss.uuuuuu'}         13:02:14.171447

$time{'yyyy/mm{on}/dd hh:mm{in}:ss.mmm'}  2003/06/05 13:02:14.171
$time{'yyyy/mm/dd hh:mm:ss.mmm'}          2003/06/05 13:02:14.171

$time{"It's H:mm."}              It'14 1:02.    # OOPS!
$time{"It'\\s H:mm."}            It's 1:02.     # Backslash fixes it.
                                                                      .
                                                                      .
# Rename a file based on today's date:
rename $file, "${file}_$time{yyyymmdd}";

# Rename a file based on its last-modify date:
rename $file, "${file}_$time{'yyyymmdd',(stat $file)[9]}";

# stftime examples
$strftime{'%A %B %d, %Y'}                 Thursday June 05, 2003
$strftime{'%A %B %d, %Y',time+86400}      Friday June 06, 2003

# manip examples
$manip{'%m/%d/%Y'}                                   06/05/2003
$manip{'%m/%d/%Y','yesterday'}                       06/04/2003
$manip{'%m/%d/%Y','first monday in November 2000'}   11/06/2000

๐ŸŒ INTERNATIONALIZATION ๐ŸŒ

If the I18N::Langinfo module is available, Time::Format will hand you weekday and month names in the language that matches the current locale ๐Ÿซถ. If it's not available? English names, periodt.

And besties in non-English locales โ€” you might wanna provide an alias to %time in your own preferred language. It's super doable, just assign "\%time" to a typeglob:

# French
use Time::Format;
use vars '%temps';  *temps = \%time;
print "C'est aujourd'hui le $temps{'d Month'}\n";

# German
use Time::Format;
use vars '%zeit';   *zeit = \%time;
print "Heutiger Tag ist $zeit{'d.m.yyyy'}\n";

slay. ๐Ÿ’…


๐ŸŽ€ EXPORTS ๐ŸŽ€

These symbols get exported into your namespace by default:

%time
time_format

And these ones are available for import into your namespace if you want 'em:

%strftime
%manip
time_strftime
time_manip

The ":all" tag will import all of these into your namespace. Example:

use Time::Format ':all';

๐Ÿ’€ LIMITATIONS ๐Ÿ’€

The format string used by %time must not have $; as a substring anywhere. fr fr, this one matters. $; (which, by default, is ASCII character 28, or 1C hex) is used to separate values passed to the tied hash โ€” so if your format string contains $;, Time::Format is gonna interpret it as two or more arguments. ๐Ÿ˜ญ

The good news: the time_format function does not have this limitation. so if $; is your whole thing, use that instead.

๐Ÿ‘‘ REQUIREMENTS ๐Ÿ‘‘

  • Time::Local
  • I18N::Langinfo, if you want non-English locales to work.
  • POSIX, if you choose to use %strftime or want the tz format to work.
  • Time::HiRes, if you want the mmm and uuuuuu time formats to work.
  • Date::Manip, if you choose to use %manip.
  • Time::Format_XS is optional but will make %time and time_format much faster ๐Ÿ”ฅ. The version of Time::Format_XS installed must match the version of Time::Format installed; otherwise Time::Format will not use it (and will issue a warning).

Copyright (c) 2003-2020 by Eric J. Roode, ROODE -at- cpan -dot- org

All rights reserved.

To avoid my spam filter, please include "Perl", "module", or this module's name in the message's subject line, and/or GPG-sign your message.

This module is copyrighted only to ensure proper attribution of authorship and to ensure that it remains available to all. This module is free, open-source software. This module may be freely used for any purpose, commercial, public, or private, provided that proper credit is given, and that no more-restrictive license is applied to derivative (not dependent) works.

Substantial efforts have been made to ensure that this software meets high quality standards; however, no guarantee can be made that there are no undiscovered bugs, and no warranty is made as to suitability to any given use, including merchantability. Should this module cause your house to burn down, your dog to collapse, your heart-lung machine to fail, your spouse to desert you, or George Bush to be re-elected, I can offer only my sincere sympathy and apologies, and promise to endeavor to improve the software. ๐Ÿ˜ญ


and that's a wrap on Time::Format(3pm) bestie ๐Ÿ’… this copy lives in perl v5.36.0, dated 2022-10-13. go format something iconic โœจ๐Ÿฆ‹๐ŸŒธ
๐Ÿ“ฆ where this page comes from