google-earth-engine – Subsetting Image Collection by Specific Dates in Google Earth Engine

dategoogle-earth-engine

I am trying to subset an image collection by a list of dates. However, I keep getting the error that my dates are not interpretable.

The date list comes from an imported csv with a list of dates.

var pts = ee.FeatureCollection('users/user/lu_long_pres_ES');
var pts_buffer = pts.map(bufferPoints(500, false));


//read in image collection
var climate = ee.ImageCollection("IDAHO_EPSCOR/TERRACLIMATE")
  .filterDate(startDate, endDate)

///read in date list and subset image collection to dates
var dates = ee.FeatureCollection('users/user/dates')
var date2list = dates.reduceColumns({
                    reducer: ee.Reducer.toList().repeat(1),
                    selectors: ['date']
                  })
                   .get('list');

var date_list = ee.List(date2list).map(function(date){return ee.Date(date).millis()});
print(date_list)

var climate = climate.map(function(image){
  return image.set('simpleTime', ee.Date(image.date().format('YYYY-MM-dd')).millis());
});

var climate_sub = climate.filter(ee.Filter.inList("simpleTime", date_list));

How can I convert the column of dates from the csv to a list of dates interpretable by google earth engine?

The csv with dates is linked here.

The full code can be found here:
https://code.earthengine.google.com/74db7bc86d1efeee21c32da0357e8d40

Best Answer

There are two tricks you need to modify to the original script so it can work fine. The first one is that in the original script the date2list object corresponds to a list with the dates inside another list (you can print the object to analyse its structure in the console). So to fix this, you should flatten the list to get rid of the nested structure. Afterwards, you should use ee.Date.parse to convert the String into a Date. However, the second trick is that the date entries contain a pair of double quotes (""), so you need to include these quotes in the format string. Here's the only modifications you need to make to your script so it works:

var date2list = ee.List(dates.reduceColumns({
                    reducer: ee.Reducer.toList().repeat(1),
                    selectors: ['date']
                  })
                   .get('list'))
                   .flatten();

var date_list = date2list.map(function(date){
  return ee.Date.parse({format:'"y-M-d"',
                        date: ee.String(date)})
                        .millis();
});