Convert a date string specifying the pattern in Pharo 8

Viewed 207

'04/30/2019' asDate works, but '30/04/2019' asDate fails because the date format of this date is in the 'dd/MM/yyyy' format.

How do I specify different time format in Pharo 8?

1 Answers

There are several ways to get a Date from a String. In your case, one that would work is the following

   Date readFrom: '30/4/2019' readStream pattern: 'dd/m/yyyy'

The 'm' in the pattern will match two digit month indexes too. If you use 'mm' instead your month indexes must have two digits, e.g., '04'.

There is nothing similar for DateAnTime. However you can do the following:

   | stream |
   stream := '30/4/2019 18:11:03' readStream.
   date := Date readFrom: (stream upTo: $ ) readStream pattern: 'dd/m/yyyy'.
   time := Time readFrom: stream.
   ^DateAndTime date: date time: time.

This uses the first part of the stream (up to the space) for the date and then continues with the time. Note that the stream is left at the character next to the space, which should be where the time begins.

Related