Search code examples
javascriptphotoshop-script

How to sort by created time when use .getFiles() in Photoshop Script?


var fileFolderArray = Folder( "~/Downloads/" ).getFiles();

How to sort by files created time when use getFiles function ? thanks:)


Solution

  • You'll be able to get the created time with .created notation. You can't use filter or more complex JavaScript functions as Photoshop relies on earlier version of ECMAScript :(

    This will work for ya:

    myFolder = "C:\\temp";
    
    var sorted = sort_files_by_creation_date(myFolder);
    var msg ="";
    for (var i = 0;  i < sorted.length; i++)
    {
       msg+= sorted[i][0] + "\n";
    }
    
    alert(msg);
    
    function sort_files_by_creation_date (afolder)
    {
    
       var fileFolderArray = Folder(afolder).getFiles();
    
       var dates = [];
       for (var i = 0;  i < fileFolderArray.length; i++)
       {
          var fileCreationDate = fileFolderArray[i].created.toString();
          // var fileCreationDate = fileFolderArray[i].modified.toString();
          dates.push([fileCreationDate, fileFolderArray[i]]);
       } 
    
       //dates.sort()
       return dates.sort(sortFunction);  
    }
    
    function sortFunction(a, b)
    {
        if (a[0] === b[0])
        {
          return 0;
        }
        else
        {
          return (a[0] < b[0]) ? -1 : 1;
        }
    }
    

    Sort function taken from here.