Project

General

Profile

Actions

Feature #16637

open

Time#to_s and Date#to_s accept strftime format string

Added by ttilberg (Tim Tilberg) about 4 years ago. Updated about 4 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:97179]

Description

While terms like strftime and strptime are ubiqutous through the history of computer science, I feel that the terms are very dense. If you are not already in-the-know, they are gibberish. If you are in the know, they are still a bit clunky. While discussing ways to improve the Time and Date formatting APIs for humanity, I thought a quick and easy improvement would be removing the need to use the method #strftime. #format is already reserved as a private method, but how do people feel about allowing a format string as an argument for #to_s?

I'm not comfortable writing C, but the relevant code is here

It seems like it would be straightforward to use the current strings as default values, but to allow for a format string to be passed in.

time_to_s(VALUE time) // add format arg
{
    struct time_object *tobj;

    GetTimeval(time, tobj);
    if (TZMODE_UTC_P(tobj))
        return strftimev("%Y-%m-%d %H:%M:%S UTC", time, rb_usascii_encoding());  // format || "%Y-%m-%d %H:%M:%S UTC"
    else
        return strftimev("%Y-%m-%d %H:%M:%S %z", time, rb_usascii_encoding());   // format || "%Y-%m-%d %H:%M:%S %z"
}

This would allow an API that feels a bit more intuitive. You still have to know the formatting symbols, but it creates a much more expressive statement:

# The current time, to string. What kind of string? A Y-m-d string.
Time.now.to_s('%Y-%m-%d')

(As an aside for discussion, I feel this way about formatting things like Floats and other numbers also. That API is equally confusing, and a holdover from history in comp-sci.)

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0