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

问题描述 投票:1回答:2

这可能很简单。我在从日期字符串中获取正确的日期格式以在动态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

错误

System.QueryException: line 1:1082 no viable alternative at character ' '
salesforce apex-code
2个回答
0
投票

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

示例:

SOQLString + ' and Date_Incurred__c >= :sd'

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;
}

其中value是Date变量

© www.soinside.com 2019 - 2024. All rights reserved.