简体   繁体   English

如何使用 linq 将日期时间 sql 转换为 c#?

[英]How may I convert the datetime sql to c# by using linq?

Below is my sql code: SELECT * FROM test.operator_error_transaction WHERE operator_token = 12345 && transaction_date_time BETWEEN '2019-05-22';下面是我的 sql 代码: SELECT * FROM test.operator_error_transaction WHERE operator_token = 12345 && transaction_date_time BETWEEN '2019-05-22';

I have tried my c# code below and got some error in comparing the datetime:我在下面尝试了我的 c# 代码,但在比较日期时间时遇到了一些错误:

var id = (from firstn in _context.OperatorErrorTransaction
                  where firstn.OperatorToken == "12345"
                  where firstn.TransactionDateTime >= '2019-05-22'
                  select firstn).ToList();
        return Ok(id);

You should use DateTime type for conversion.您应该使用 DateTime 类型进行转换。

 var mydate = Convert.ToDateTime("2019-05-22");
 var id = (from firstn in _context.OperatorErrorTransaction
                  where firstn.OperatorToken == "12345"
                  where firstn.TransactionDateTime >= mydate 
                  select firstn).ToList();
        return Ok(id);

Convert your string to datetime.将您的字符串转换为日期时间。 This will work.这将起作用。

Convert.ToDateTime("2019-05-22")

I'd suggest:我建议:

var startInclusive= new DateTime(2019,5,22); // if you really must, use `DateTime.TryParseExact` here
var endExclusive = startInclusive.AddDays(1);

var id = (from firstn in _context.OperatorErrorTransaction
            where firstn.OperatorToken == "12345"
                  && firstn.TransactionDateTime >= startInclusive
                  && firstn.TransactionDateTime < endExclusive
            select firstn).ToList();
return Ok(id);

This avoids any issues relating to culture and date formats.这避免了与文化和日期格式相关的任何问题。 And it gets all data where the transaction occurred someone on 22 May 2019 (whatever the time component) and has good performance characteristics .并且它获取交易发生在 2019 年 5 月 22 日某人的所有数据(无论时间部分)并且具有良好的性能特征

sql date format is YYYY-MM-DD and c# date format is DD-MM-YYYY. sql 日期格式为 YYYY-MM-DD,c# 日期格式为 DD-MM-YYYY。

Please change either of the date formats.请更改任一日期格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM