2014-11-06 38 views
0

的操作數,我使用LINQ查詢,但得到錯誤 Cannot apply operator >= to operands of type system.datetime and string得到錯誤不能申請運營商類型的System.DateTime和字符串

這裏是我的LINQ查詢

var myBirthDate= BirthDate.ToString("yyyy-MM-dd HH':'mm':'ss"); 

var myList= (from myEntity in myEntityRepository.AsQueryable() 
           where 
            myEntity.id== Id && 
            myEntity.birthdate >= myBirthDate 
           select myEntity).Take(1); 

我轉換日期到yyyy-MM-dd HH':'mm':'ss格式因爲我從客戶端獲得其他格式。

我該如何避免此錯誤?

+1

異常消息是自我描述性的! – 2014-11-06 10:09:51

回答

1

這將導致一個字符串使用ToString()方法之後,而不是一個日期時間

var myBirthDate= BirthDate.ToString("yyyy-MM-dd HH':'mm':'ss"); 

使用DateTime.TryParse獲得由客戶提供的價值日期時間。然後在你的查詢中使用它。

1

如果您收到的日期與當前文化不同,您可以使用DateTime.Parse轉換爲正確的DateTime變量。

由於您正在使用ToString將DateTime類型轉換爲格式化的日期字符串,因此myBirthDate變量將成爲String,因此> =將無法按預期工作。

下面是一個示例:

using System; 

public class Example 
{ 
    public static void Main() 
    { 
     string[] dateStrings = {"2008-05-01T07:34:42-5:00", 
           "2008-05-01 7:34:42Z", 
           "Thu, 01 May 2008 07:34:42 GMT"}; 
     foreach (string dateString in dateStrings) 
     { 
     DateTime convertedDate = DateTime.Parse(dateString); 
     Console.WriteLine("Converted {0} to {1} time {2}", 
          dateString, 
          convertedDate.Kind.ToString(), 
          convertedDate); 
     }        
    } 
} 
+0

不知道我怎麼能適合你的答案,根據我的問題。你能再次檢查你的答案嗎? – Happy 2014-11-06 10:20:50

+0

你的問題很清楚。該行var myBirthDate = BirthDate.ToString(「yyyy-MM-dd HH':​​'mm':'ss」);生成一個字符串變量,因此你不能使用> =來比較它。您需要將其轉換爲DateTime類型才能比較日期。 – 2014-11-06 10:22:57