Module datetime::format [] [src]

Date and Time Formatting

There are various competing standards for how a date-time formatting string should look: Unix-style strftime with % symbols and flags, Joda-style formatters that use the number of letters as their widths, and many others, each with their own idiosyncrasies and subtle differences. Thus, it should come as no surprise that this library invents another style of formatting string, designed to mimic the syntax of the format! and println! macros.

In order to format a date, you must first create a formatter object, passing in a formatting string. This string is checked for correctness, after which it's guaranteed to always work. For example:

use datetime::format::DateFormat;
let formatter = match DateFormat::parse("{_:M} {:D}, {:Y}") {
    Ok(f) => f,
    Err(e) => panic!("Error in format string: {}", e),
};

If there's a syntax error in the formatting string, the Err(e) path will be followed, terminating the program and printing out an error. (It's usually considered better style to handle your errors more gracefully than this.) For this reason, it's preferable to use the date_format! macro whenever your formatting string is fixed, as this will check its syntax at compile-time, reporting an error if it is invalid, and removing the need for the match construct entirely:

use datetime::format::DateFormat;
let formatter = date_format!("{_:M} {:D}, {:Y}");

Locales

The second thing you need to be aware of before actually being able to format a date into a string is the concept of locales. A Locale object specifies how the months and days should be named. "January" isn't universally understood: in some places it's "janvier"; in others, "Janeiro", or "Ιανουαρίου", or "января", or "一月".

To govern which language a formatter should use, a Locale object can be passed in. For more information on how Locale objects work, see the documentation on the Locale crate.

If you're in a hurry and just want to format a date right now then the simplest way to get around this is to just use the English locale:

use locale;
let my_locale = locale::Time::english();

Actually Formatting a Date

Structs

Arguments
DateFormat
NumArguments
TextArguments

Enums

Field
FormatError

Type Definitions

Pos
Width