Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date Comparing in C#

Tags:

date

c#

datetime

i'm currently working on a little project and i'm stuck with a little problem. I would like my program to call a method CheckDate on boot. This method would read in a .txt file to see the last saved date in (yyyy/mm/dd) format. Then it would compare it with todays date and if it's not the same go on with some instructions.I've read the doc here but can't quite find which method best suites my need.

Question 1: Is there a way to get today's date in (yyyy/mm/dd) format?

Question 2: What's the easiest way to compare Dates in C#?

Thanks in advance.

like image 851
phadaphunk Avatar asked Aug 01 '26 16:08

phadaphunk


2 Answers

1. DateTime.Now.ToString("yyyy/MM/dd")
2. DateTime.Parse(input).Date == DateTime.Now.Date
like image 165
Bashwork Avatar answered Aug 04 '26 05:08

Bashwork


You can get today's date as a string by simply formatting a date.

String today = String.Format("{0: yyyy/MM/dd}", DateTime.Now); 
String today = DateTime.Now.ToString("yyyy/MM/dd");

I would advise against using a text file as your means of saving data but if you are going with that system the only thing you would have to do is check to see if the date from the text file matches the date you formatted. Simply comparing formatted strings should do the trick.

if (string a == string b)

You could even put it in one line without having to format stuff separately

if (DateTime.Now.ToString("yyyy/MM/dd").Equals("date pulled from txt file"))
like image 29
Chase Avatar answered Aug 04 '26 04:08

Chase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!