C#中的日期比较 [英] Date Comparing in C#

查看:165
本文介绍了C#中的日期比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开展一个小项目,我遇到了一些问题。
我希望我的程序在启动时调用方法 CheckDate
此方法将读入 .txt 文件,以(yyyy / mm / dd)格式查看上次保存的日期。
那么它会与今天的日期进行比较,如果它不一样的一些说明。我读了这个文档这里,但是找不到最适合我需要的方法。

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.

问题1:是有一种方法可以在(yyyy / mm / dd)格式中获取今天的日期?

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

问题2:最简单的方法是比较日期C#?

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

提前感谢

推荐答案

通过简单格式化日期作为字符串日期。

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)

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"))

这篇关于C#中的日期比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆