Obtain and reformat the from and to dates
        into a date query construct
163708
def formatDateQuery(context, date_id):
    
    from_date = context.REQUEST.get('%s_fromdate' % date_id, None)
    if from_date:
        from_date = from_date + ' 00:00'
    to_date = context.REQUEST.get('%s_todate' % date_id, None)
    if to_date:
        to_date = to_date + ' 23:59'

    date_query = {}
    if from_date and to_date:
        date_query = {'query': [from_date, to_date],
                      'range': 'min:max'}
    elif from_date or to_date:
        date_query = {'query': from_date or to_date,
                      'range': from_date and 'min' or 'max'}

    return date_query
804862
function getFormattedDate(date, lang, type) {
        date = date || new Date();
        lang = lang || 'en';
        type = type || 'long';

        // set the language for en
        if (lang === 'en' && type === 'short') { lang = 'enshort'; }
        if (lang === 'en' && type === 'medium') { lang = 'enmedium'; }

        // get the date string
        return moment(date).locale(lang).fromNow();
    }
1011638
function getDateTranslation(date, locale, name, width, form, extended) {
    switch (name) {
        case TranslationType.Months:
            return getLocaleMonthNames(locale, form, width)[date.getMonth()];
        case TranslationType.Days:
            return getLocaleDayNames(locale, form, width)[date.getDay()];
        case TranslationType.DayPeriods:
            var /** @type {?} */ currentHours_1 = date.getHours();
            var /** @type {?} */ currentMinutes_1 = date.getMinutes();
            if (extended) {
                var /** @type {?} */ rules = getLocaleExtraDayPeriodRules(locale);
                var /** @type {?} */ dayPeriods_1 = getLocaleExtraDayPeriods(locale, form, width);
                var /** @type {?} */ result_1;
                rules.forEach(function (rule, index) {
                    if (Array.isArray(rule)) {
                        // morning, afternoon, evening, night
                        var _a = rule[0], hoursFrom = _a.hours, minutesFrom = _a.minutes;
                        var _b = rule[1], hoursTo = _b.hours, minutesTo = _b.minutes;
                        if (currentHours_1 >= hoursFrom && currentMinutes_1 >= minutesFrom &&
                            (currentHours_1 < hoursTo ||
                                (currentHours_1 === hoursTo && currentMinutes_1 < minutesTo))) {
                            result_1 = dayPeriods_1[index];
                        }
                    }
                    else {
                        // noon or midnight
                        var hours = rule.hours, minutes = rule.minutes;
                        if (hours === currentHours_1 && minutes === currentMinutes_1) {
                            result_1 = dayPeriods_1[index];
                        }
                    }
                });
                if (result_1) {
                    return result_1;
                }
            }
            // if no rules for the day periods, we use am/pm by default
            return getLocaleDayPeriods(locale, form, /** @type {?} */ (width))[currentHours_1 < 12 ? 0 : 1];
        case TranslationType.Eras:
            return getLocaleEraNames(locale, /** @type {?} */ (width))[date.getFullYear() <= 0 ? 0 : 1];
    }
}
1123799
def get_headers(self, date_headers, from_date, to_date, trunc):
        """"""
        date_headers = list(date_headers)

        # Earliest date should be no earlier than from_date.
        if date_headers and date_headers[0] < from_date:
            date_headers[0] = from_date

        # When organizing by week or month, create a list of the range for
        # each date header.
        if date_headers and trunc != 'day':
            count = len(date_headers)
            range_headers = [0] * count
            for i in range(count - 1):
                range_headers[i] = (
                    date_headers[i], date_headers[i + 1] - relativedelta(days=1))
            range_headers[count - 1] = (date_headers[count - 1], to_date)
        else:
            range_headers = date_headers
        return date_headers, range_headers
595659
def _compile_update_from(self, query):
        
        if not query.joins:
            return ""

        froms = []

        for join in query.joins:
            froms.append(self.wrap_table(join.table))

        if len(froms):
            return " FROM %s" % ", ".join(froms)

        return ""
891609
def find_by_date_interval(from, unto)
      response = request(:find_by_date_interval, "first" => from.iso8601,
                                                 "last" => unto.iso8601)

      handle_key = "#{Support::String.underscore(entity_class_name)}_handle".intern
      handles = [response[handle_key]].flatten.reject(&:blank?).collect do |handle|
        Entity::Handle.build(handle)
      end

      get_data_array(handles).collect do |entity_hash|
        entity = build(entity_hash)
        entity.persisted = true
        entity
      end
    end
1245650
def format_query(area=None, date=None, raw=None, area_relation='Intersects',
                     **keywords):
        
        if area_relation.lower() not in {"intersects", "contains", "iswithin"}:
            raise ValueError("Incorrect AOI relation provided ({})".format(area_relation))

        # Check for duplicate keywords
        kw_lower = set(x.lower() for x in keywords)
        if (len(kw_lower) != len(keywords) or
                (date is not None and 'beginposition' in kw_lower) or
                (area is not None and 'footprint' in kw_lower)):
            raise ValueError("Query contains duplicate keywords. Note that query keywords are case-insensitive.")

        query_parts = []

        if date is not None:
            keywords['beginPosition'] = date

        for attr, value in sorted(keywords.items()):
            # Escape spaces, where appropriate
            if isinstance(value, string_types):
                value = value.strip()
                if not any(value.startswith(s[0]) and value.endswith(s[1]) for s in ['[]', '{}', '//', '()']):
                    value = re.sub(r'\s', r'\ ', value, re.M)

            # Handle date keywords
            # Keywords from https://github.com/SentinelDataHub/DataHubSystem/search?q=text/date+iso8601
            date_attrs = ['beginposition', 'endposition', 'date', 'creationdate', 'ingestiondate']
            if attr.lower() in date_attrs:
                # Automatically format date-type attributes
                if isinstance(value, string_types) and ' TO ' in value:
                    # This is a string already formatted as a date interval,
                    # e.g. '[NOW-1DAY TO NOW]'
                    pass
                elif not isinstance(value, string_types) and len(value) == 2:
                    value = (format_query_date(value[0]), format_query_date(value[1]))
                else:
                    raise ValueError("Date-type query parameter '{}' expects a two-element tuple "
                                     "of str or datetime objects. Received {}".format(attr, value))

            # Handle ranged values
            if isinstance(value, (list, tuple)):
                # Handle value ranges
                if len(value) == 2:
                    # Allow None to be used as a unlimited bound
                    value = ['*' if x is None else x for x in value]
                    if all(x == '*' for x in value):
                        continue
                    value = '[{} TO {}]'.format(*value)
                else:
                    raise ValueError("Invalid number of elements in list. Expected 2, received "
                                     "{}".format(len(value)))

            query_parts.append('{}:{}'.format(attr, value))

        if raw:
            query_parts.append(raw)

        if area is not None:
            query_parts.append('footprint:"{}({})"'.format(area_relation, area))

        return ' '.join(query_parts)
1329657
function weekFormat() {

  const format = function(d) {
    return formatWeekYear(d) + "w" + formatWeek(d);
  };

  format.parse = function parse(dateString) {
    const matchedDate = dateString.match(/^(\d{4})w(\d{2})$/);
    return matchedDate ? getDateFromWeek(matchedDate[1], matchedDate[2]) : null;
  };

  const formatWeekYear = function(d) {
    if (!(d instanceof Date)) d = new Date(+d);
    return new Date(+d + ((4 - (d.getUTCDay() || 7)) * 86400000)).getUTCFullYear();
  };

  const formatWeek = function(d) {
    if (!(d instanceof Date)) d = new Date(+d);
    const quote = new Date(+d + ((4 - (d.getUTCDay() || 7)) * 86400000));
    const week = Math.ceil(((quote.getTime() - quote.setUTCMonth(0, 1)) / 86400000 + 1) / 7);
    return week < 10 ? "0" + week : week;
  };

  const getDateFromWeek = function(p1, p2) {
    const week = parseInt(p2);
    const year = p1;
    const startDateOfYear = new Date(); // always 4th of January (according to standard ISO 8601)
    startDateOfYear.setUTCFullYear(year);
    startDateOfYear.setUTCMonth(0);
    startDateOfYear.setUTCDate(4);
    const startDayOfWeek = startDateOfYear.getUTCDay() || 7;
    const dayOfWeek = 1; // Monday === 1
    const dayOfYear = week * 7 + dayOfWeek - (startDayOfWeek + 4);

    let date = formats["year"].data.parse(year);
    date = new Date(date.getTime() + dayOfYear * 24 * 60 * 60 * 1000);

    return date;
  };

  return format;

}
1140999
def add_filter_by_date(self, query, out_params):
        
        date_query = formatDateQuery(self.context, 'Requested')
        if date_query:
            query['created'] = date_query
            requested = formatDateParms(self.context, 'Requested')
            out_params.append({'title': _('Requested'),
                               'value': requested,
                               'type': 'text'})
912551
function to (date, term) {
  if (!term) {
    return null;
  }
  var se = this.getRange(date, term);
  return se ? se.to : null;
}
1180449
function from (date, term) {
  if (!term) {
    return null;
  }
  var se = this.getRange(date, term);
  return se ? se.from : null;
}
786514
function makeDateStr(date, sep) {
	if (sep === undefined) sep = true;

	var year = date.getUTCFullYear().toString(),
		month = padNum(date.getUTCMonth()+1),
		day = padNum(date.getUTCDate()),
		hours = padNum(date.getUTCHours()),
		minutes = padNum(date.getUTCMinutes()),
		seconds = padNum(date.getUTCSeconds());

	if (sep) {
		return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
	} else {
		return year + month + day + hours + minutes + seconds;
	}
}
150968
function deserializeQueryParam(param) {
  if (!!param && (typeof param === 'object')) {
    if (param.__type === 'Date') {
      return new Date(param.iso);
    }
  }
  return param;
}
611659
def get_period(date_from: date, date_to: date) -> str:
    
    assert isinstance(date_from, date)
    assert isinstance(date_to, date)

    str_from: str = date_from.isoformat()
    str_to: str = date_to.isoformat()

    return str_from + " - " + str_to
1067604
def _to_desired_dates(self, arr):
        """"""
        times = utils.times.extract_months(
            arr[internal_names.TIME_STR], self.months
        )
        return arr.sel(time=times)
887333
def temporal_from_literal(text):
    '''
    
    '''
    if text.count('/') == 1:
        # This is an ISO date range as preconized by Gov.uk
        # http://guidance.data.gov.uk/dcat_fields.html
        start, end = text.split('/')
        return db.DateRange(
            start=parse_dt(start).date(),
            end=parse_dt(end).date()
        )
    else:
        separators = text.count('-')
        if separators == 0:
            # this is a year
            return db.DateRange(
                start=date(int(text), 1, 1),
                end=date(int(text), 12, 31)
            )
        elif separators == 1:
            # this is a month
            dt = parse_dt(text).date()
            return db.DateRange(
                start=dt.replace(day=1),
                end=dt.replace(day=calendar.monthrange(dt.year, dt.month)[1])
            )
755741
function addDayToRange(day) {
  var range = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { from: null, to: null };
  var from = range.from,
      to = range.to;

  if (!from) {
    from = day;
  } else if (from && to && isSameDay(from, to) && isSameDay(day, from)) {
    from = null;
    to = null;
  } else if (to && isDayBefore(day, from)) {
    from = day;
  } else if (to && isSameDay(day, to)) {
    from = day;
    to = day;
  } else {
    to = day;
    if (isDayBefore(to, from)) {
      to = from;
      from = day;
    }
  }

  return { from: from, to: to };
}