Effective String to Date conversion?

atzensepp webwicht at web.de
Mon Jan 22 10:56:04 UTC 2024


Dear D-gurus,

being new to D I am trying my first steps and the language is 
quite intuitive and appealing.
When reading a file and creating a hash for the reocrds I want to 
get only the most recent ones. For this I need to convert 
Date/Time-Strings to comparable DateTime-Objects.
The code below works but looks a bit clumsy. Is there a more 
efficient (shorter) way to accomplish this?

Thanks in advance


```d
// Read lines using foreach.
void main( string args[])
{
     auto file = File(args[1]);// Open for reading
     auto range = file.byLineCopy();
     auto iline=0;
     int  idxARE=2,idxDC=3,idxTD=0;

     string [] records[string];

     DateTime getDateTime( string [] row)
     {
         int d,m,y,ho,mi,se;
         row[0].formattedRead!"%d.%d.%d"(d, m, y);
         row[1].formattedRead!"%d:%d:%d"(ho, mi, se);
         return DateTime(y,m,d,ho,mi,se);
     }

     foreach (line; range)
     {
         if (!line.empty)
         {
             string [] row = line.split(";");

             string key = [row[2], row[3]].join("_"); // unique key
             if(iline>0) // skip header line
             {
                if(key in records)
                {
                   // do we have a newer one?
                   if( getDateTime(row) > 
getDateTime(records[key]))
                   {
                      records[key]=row;
                      writeln("UPDATE:",key);
                   }
                } else
                {
                   // first one:
                   records[key]=row;
                }
               }
             iline++;
         }
     }

     writeln( records.length);
     writeln("Lines: ",i);
}

```


More information about the Digitalmars-d-learn mailing list