Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

c# - Retrieve a string from database and compare with date

I have a field in database stored as string and i need to convert it back to datetime and then compare if it equals to date. Below is the current implementation I have presently.

var date = DateTime.UtcNow ;
        var zone = TimeZoneInfo.FindSystemTimeZoneById("W. Central Africa Standard Time");           
        DateTime currentTime = TimeZoneInfo.ConvertTimeFromUtc(date, zone);
        var loanDate = currentTime.Date.ToString("dd/MM/yyyy").Replace("-", "/");


if (DateTime.ParseExact(firstRepay, "dd/MM/yyyy", CultureInfo.InvariantCulture).Date.ToString("dd/MM/yyyy").Replace("-", "/") == WATTime.Date.ToString("dd/MM/yyyy").Replace("-", "/"))
  { // Do this
}

note that the firstRepay is in the format 06/02/2021 in the database but it might be 06-02/2021 depending on server format.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming loanDate and dbDate are in the same format "dd/MM/yyyy" and the dbDate also can be in "dd-MM/yyyy" format, you can try this code

var dateFromDb="01-02/2021"; // 1 Feb 2021
var loanDate="06/02/2020";  // 6 Feb 2020
var dbDate =  dateFromDb.Replace("-", "/"); 
    
var dbDateTime = DateTime.ParseExact(dbDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);

var loanDateTime= DateTime.ParseExact(loanDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
     
var diffDateDays=(dbDateTime-loanDateTime).Days; // = 361
    
//or you can use it this way:
    
if ((dbDateTime-loanDateTime).Days > 0) //.... then

If dates are in a different string format you just have to change string "dd/MM/yyyy" to "MM/dd/yyyy" for example for this date, but the algorithm will be still the same.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...