How to get the start and end times of a day

后端 未结 10 749
无人及你
无人及你 2020-12-24 00:29

In my C# app, I pass a string variable that is of format yyyymmdd-yyyymmdd that represents a from and to date. I want to get the start and end times for these dates respecti

10条回答
  •  不知归路
    2020-12-24 00:57

    That's pretty much what I would do, with some small tweaks (really no big deal, just nitpicking):

    • The TryParse()/TryParseExact() methods should be used which return false instead of throwing exceptions.
    • FormatException is more specific than Exception
    • No need to check for Length == 8, because ParseExact()/TryParseExact() will do this
    • "00:00:00" and "23:59:59" are not needed
    • return true/false is you were able to parse, instead of throwing an exception (remember to check value returned from this method!)

    Code:

    private bool ValidateDatePeriod(string pdr, out DateTime startDate, 
                            out DateTime endDate)
    {
       string[] dates = pdr.Split('-');
    
       if (dates.Length != 2)
       {
           return false;
       }
    
       // no need to check for Length == 8 because the following will do it anyway
       // no need for "00:00:00" or "23:59:59" either, I prefer AddDays(1)
    
       if(!DateTime.TryParseExact(dates[0], "yyyyMMdd", null, DateTimeStyles.None, out startDate))
          return false;
    
       if(!DateTime.TryParseExact(dates[1], "yyyyMMdd", null, DateTimeStyles.None, out endDate))
          return false;
    
       endDate = endDate.AddDays(1);
       return true;
    }
    

提交回复
热议问题