[Pharo-dev] Formatting dates
Sven Van Caekenberghe
sven at stfx.eu
Wed Oct 30 18:11:01 EDT 2013
On 30 Oct 2013, at 22:46, Nicolas Cellier <nicolas.cellier.aka.nice at gmail.com> wrote:
> Why not a more discriminating example, like '19991231’?
From the class comment:
You instanciate me by specifying the textual format by example, based on a #reference timetamp.
Each component of the example representation is numbered from largest to smallest unit, 1=year, 2=month, 3=dayInMonth, 4=hour (16 in 24 hour format), 5=minute and 6=second, as in the ISO representation: 2001-02-03T16:05:06Z which is a Saterday. Example format strings can be found in my class accessing protocol or in the unit tests.
But of course, internally there is less magic: it are just specific keys/tokens that are recognised ;-) The example is kind of compiled though to make it more efficient should you reuse the format.
> 2013/10/30 Sven Van Caekenberghe <sven at stfx.eu>
> Hi Blake,
> On 30 Oct 2013, at 21:55, blake <dsblakewatson at gmail.com> wrote:
> > Heya, guys--
> > Converting a Ruby program to Pharo, and one of the things this program does is write a file out by date. The format is "yyyymmdd" (which is my preferred naming convention). In Ruby I have:
> > "%04d" % d.year + "%02d" % d.month + "%02d" % d.day
> > In Smalltalk, the closest I can seem to get to this is:
> > d year asString, (d monthIndex asString padLeftTo: 2 with: $0), (d dayOfMonth asString padLeftTo: 2 with: $0)
> > ...which seems sort verbose. Anyone have any more elegant solutions?
> Using the ‘by example’ formatter/parser that is part of the ZTimestamp package (can be loaded using the Configuration Browser), you could say:
> (ZTimestampFormat fromString: '20010203') format: Date today.
> Although it is called ZTimestampFormat, it can actually work with Date, Time, DateAndTime as well.
More information about the Pharo-dev