简体   繁体   中英

How to check for date in C# textbox and display whether the date is before or later than DateTime.Now

I have a windows form program that reads from txt files and displays them in a textbox, the output can be`"Test w/c 07/03/16 AT 21/04/2016" or "AT 09/05/2016" or "w/c 07/03/2016 AT 17/03/2016 w/c 25/04/2016". I am loading 7 text files into it, some contain either 1, 2 or 3 dates.

How would I detect these dates and be able to output whether the dates detected are before or after DateTime.Now ?

If your string is always in "Test w/c dd/MM/yy AT dd/MM/yyyy" format, you can Split your string with white space, take the relevant strings, parse them to DateTime with ParseExact and compare them with DateTime.Now value.

var s = "Test w/c 07/03/16 AT 21/04/2016";
var arr = s.Split(' ');
var firstDate = DateTime.ParseExact(arr[2], "dd/MM/yy", CultureInfo.InvariantCulture);
var secondDate = DateTime.ParseExact(arr[4], "dd/MM/yyyy", CultureInfo.InvariantCulture);

and you can compare them like;

if(firstDate < DateTime.Now)
// before
if(firstDate > DateTime.Now)
//after
if(secondDate < DateTime.Now)
// before
if(secondDate > DateTime.Now)
//after
if(firstDate < DateTime.Now && secondDate < DateTime.Now)
//Both before
if(firstDate > DateTime.Now && secondDate > DateTime.Now)
//Both after
etc..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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