Salesforce Apex:动态查询中的日期字符串到日期问题

时间:2013-09-18 15:25:02

标签: salesforce apex-code

这可能很简单。我在从日期字符串中获取正确的日期格式以在动态SOQL语句的where子句中使用时遇到问题。我尝试了日期函数的变体,但仍然无法找出正确的格式。自定义对象字段的类型为Date。感谢所有建议,谢谢。

public string startDate {get;set;}
public string endDate {get;set;}

public void mymethod(){

   string SOQLString = 'SELECT Id, Name FROM Time__c WHERE Closed__c = true';

   if(startDate != null && endDate != null && startDate.length() > 0 && endDate.length() > 0)
   {
      Date sd = Date.Parse(startDate);
      Date ed = Date.Parse(endDate);

      SOQLString = SOQLString + ' and Date_Incurred__c >= ' + sd + ' and Date_Incurred__c <= ' + ed;
      //SOQLString = SOQLString + ' and Date_Incurred__c >= \'' + sdt + '\' and Date_Incurred__c <= \'' + edt + '\'';
}

   List<Time__c> times = Database.Query(SOQLString);
   ...

SOQLString的输出

SELECT Id, Name FROM Time__c WHERE Closed__c = true and Date_Incurred__c >= 2013-09-27 00:00:00 and Date_Incurred__c <= 2013-09-02 00:00:00

ERROR

System.QueryException: line 1:1082 no viable alternative at character ' '

2 个答案:

答案 0 :(得分:0)

我们可以使用带冒号的引号内的变量。所以它会自动替换变量值。

示例:

SOQLString + ' and Date_Incurred__c >= :sd'

答案 1 :(得分:0)

如果需要在动态查询(Database.query())中使用它,则可以使用以下代码:

if (value == null) {
    value = 'null';
} else if (value instanceof Date) {
    Date dateValue = (Date) value;
    String monthString = String.valueof(dateValue.month());
    monthString = dateValue.month() < 10 ? '0' + monthString : monthString;
    String dayString = String.valueof(dateValue.day());
    dayString = dateValue.day() < 10 ? '0' + dayString : dayString;
    value = dateValue.year() + '-' + monthString + '-' + dayString;
}

其中值是日期变量