cient date parsing
> 
> 
> I have a large file with dates in the format '2001-11-04'. As 
> I couldn't find a method to change to date, I'm doing:
>       date := self dateFrom: (dateString  subStrings: '-').
> 
> dateFrom: anArray
>       "anArray should be like #('2005' '09' '06')"
>       ^Date year: anArray first asInteger month: anArray 
> second asInteger day:
> anArray third asInteger
> 
> This works, but profiling shows half the work in loading the 
> file is in
> dateFrom:
> 
> Is there a more efficient way? Is there a standard method I've missed?

On my Date class, class side, I use the following extention methods for
parsing dates.

fromString: aString format: aFormat 
        aFormat = #dmy
                ifTrue: [^ self readEuro: aString readStream ].
        aFormat = #iso8601
                ifTrue: [^ self readISO: aString readStream].
        ^ self fromString: aString

readEuro: aStream 
        "Read a Date in euro format dd-mm-yyyy"
        | day month year |
        aStream skipSeparators.
        day := Integer readFrom: aStream.
        [aStream peek isDigit]
                whileFalse: [aStream skip: 1].
        month := Integer readFrom: aStream.
        [aStream peek isDigit]
                whileFalse: [aStream skip: 1].
        year := Integer readFrom: aStream.
        ^ self
                newDay: day
                month: month
                year: year

readISO: aStream 
        "Read a Date in ISO-8601 format yyyy-mm-dd"
        | day month year |
        aStream skipSeparators.
        year := Integer readFrom: aStream.
        [aStream peek isDigit]
                whileFalse: [aStream skip: 1].
        month := Integer readFrom: aStream.
        [aStream peek isDigit]
                whileFalse: [aStream skip: 1].
        day := Integer readFrom: aStream.
        ^ self
                newDay: day
                month: month
                year: year

Ramon Leon
http://onsmalltalk.com

_______________________________________________
Beginners mailing list
Beginners@lists.squeakfoundation.org
http://lists.squeakfoundation.org/mailman/listinfo/beginners

Reply via email to