【问题标题】:Comparing DateTime for .NET Application比较 .NET 应用程序的日期时间
【发布时间】:2012-04-10 09:13:10
【问题描述】:

我有一个使用 Drive.Info 的小应用程序。我想做两件事。检查机器上是否存在某个驱动器,如果存在并且 todaysdate 不是存储在文本文件中的多个日期之一,请运行一个小型应用程序。如果在文本文件中读取今天的日期,则什么也不做。我有一堆代码在工作,但在使用 DateTime 对象时遇到了问题。任何人都可以看看我有什么并建议我需要重组什么吗?所有的逻辑都在那里,我只是没有正确地组合起来。

  1. 存储在我正在读取的 txt 文件中的日期在每个文件中都是如此 线路:2010 年 12 月 25 日。
  2. 在 catch 语句中的行“Console.WriteLine(e.Message);”是什么产生了“字符串未被识别为有效的日期时间”问题。
  3. 我想要的目标是:如果在文本文件中找不到今天的日期,并且在当前机器上存在“(d.Name.Contains(“C”))”行中指定的驱动器,请运行 calc.exe。
  4. 如果在文本文件中找到今天的日期,则什么也不做。

我的问题是:如何修改应用程序的结构,以便:成功地将日期与 txt 文件中存储的日期进行比较。其次,调整我的逻辑,这样我就可以实现上面的第 3 部分和第 4 部分。

很抱歉需要编辑,我最初的帖子应该更清楚。 谢谢。

编辑:伙计们,我已经更新了下面的代码。它现在似乎正在工作。感谢您的帮助,再次为第一个问题的糟糕组合感到抱歉。但是,应用程序行为现在可以正常工作;问题仍然存在(当今天的日期不在文件中,并且指定的驱动器不存在时)很高兴了解为什么会发生这种情况?

public static void Main()
/* Goal of this application: Read a text file filled with public holiday dates     formatted as: 25/12/2011
 * Compare these to today's date.  If not a match, run calc.exe ASSUMING THE SPECIFIED   DRIVE ON LINE 78
 * IS FOUND ON THE COMPUTER.  If the date matches, do nothing.
*/
{
    Process Calculator = new Process();
    Calculator.StartInfo.FileName = "calc.exe";
    Calculator.StartInfo.Arguments = "ProcessStart.cs";
    DriveInfo[] allDrives = DriveInfo.GetDrives();

    // Create a StreamReader to read from file.
    StreamReader sr = new StreamReader("file.txt");

        String DateFromFile;
        DateTime todaysDate = DateTime.Today;

        try
        {              
            // Read and display lines from the file until the eof is reached.
            while ((DateFromFile = sr.ReadLine()) != null)
            {
                Console.WriteLine(DateFromFile);
                DateTime dt = Convert.ToDateTime(DateFromFile);


                if (dt == todaysDate)
                {
                    Console.WriteLine("File.text has todays date inside! Not gonna run calc.exe");
                    Environment.Exit(0);

                }//end if 

                else
                {
                 }//end else


          }//end while
        }//end try

        catch (Exception e)
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file.txt could not be read");
            Console.WriteLine(e.Message);
       }

        ////////// DO THE REST ///////////
     foreach (DriveInfo d in allDrives)
        {
            Console.WriteLine("Drive {0}", d.Name);

            Console.WriteLine("  File type: {0}", d.DriveType);
            if (d.IsReady == true)
            {
                Console.WriteLine("  Volume label: {0}", d.VolumeLabel);
                Console.WriteLine("  File system: {0}", d.DriveFormat);
                Console.WriteLine(
                    "  Available space to current user:{0, 15} bytes",
                    d.AvailableFreeSpace);

                Console.WriteLine(
                    "  Total available space:          {0, 15} bytes",
                    d.TotalFreeSpace);

                Console.WriteLine(
                    "  Total size of drive:            {0, 15} bytes ",
                    d.TotalSize);
            }//end if
            if (d.Name.Contains("T"))
            {
                Console.WriteLine("\n");
                Console.WriteLine("** SUCCESS - LETTER FOUND **\n\n ** RUN CALC.EXE **");
                Console.WriteLine("\n");
                Calculator.Start();
            }//end if
            else
            {
                Console.WriteLine("** LETTER NOT FOUND **");
                Console.WriteLine("\n");
            }//end else  
        }//end for


}//end main
}//end class

【问题讨论】:

  • 文本文件的日期格式是什么?
  • 但在使用 DateTime 对象时遇到问题,您能否进一步扩展
  • 您对 DateTime 对象有什么问题?可以提供更多细节。
  • 如果您的格式是固定的,您可以使用DateTime.ParseExact 吗?
  • @GrumP - 你真的应该提到任何错误信息。

标签: c# .net datetime compare


【解决方案1】:

这是 StackOverflow 上的重复问题

String was not recognized as a valid DateTime " format dd/MM/yyyy"

希望对你有帮助

更改您的代码行:DateTime dt = Convert.ToDateTime(DateFromFile);

DateTime dt= DateTime.ParseExact(DateFromFile, "dd/MM/yyyy", null);

【讨论】:

  • 伤心但.Date没有时间分量
【解决方案2】:

比较日期和字符串时需要注意两点:

  1. 确保您使用正确的数据类型
  2. 确保您使用正确的格式。

因此,如果您想将 DateTime 与字符串日期进行比较,您要做的第一件事就是将字符串转换为 DateTime。

最好和最可靠的方法是预先知道字符串的格式并像这样使用 parseExact:

string myDateTimeString = "03/04/2012"; // Notice month and day are ambiguous!
string format = "dd/MM/yyyy";
DateTime dateTime = DateTime.ParseExact(myDateTimeString, format,
        CultureInfo.InvariantCulture);

使用cultureInfo 重载也很重要。只要一直这样做,您的代码就会更可靠。

现在你有了一个可以比较的 dateTime,但我不会在基础对象上使用等号运算符,而是使用这个:

if (myDate.Date == DateTime.Today)
{
   //Occurs on same day!

}

或者在你的情况下:

if (myDate.Date == DateFromTextFile.Date)
{
  //Condition met
}

【讨论】:

  • 很好的答案,谢谢。我已经更改了我的代码以使用它,因为它反映了良好的做法。 :)
【解决方案3】:

我认为您必须在开始时将当前日期转换为特定日期格式。

例如使用

String todaysDate = DateTime.Now.ToShortDateString();

当您比较时,还将字符串转换为该格式并进行比较

 String dt = DateTime.Parse(DateFromFile).ToShortDateString();

【讨论】:

  • ToShortString 创建一个字符串,而不是 DateTime
  • 阿德里安·伊夫托德,thnx 忘了改一下
  • 然后你比较字符串?
  • 你从哪里得到这个ToShortString?我能得到的最接近的是ToShortDateString
  • 阿德里安·伊夫托德,我没让你解释
猜你喜欢
  • 2016-09-19
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 2012-12-29
相关资源
最近更新 更多