Best way to get a date with .NET?

前端 未结 4 1787
太阳男子
太阳男子 2021-02-20 07:56

I\'m getting a string back from my page and I want to make sure it\'s a date. This is what I have so far (it works) and I just want to know if this is the \"best\" way to do it.

相关标签:
4条回答
  • 2021-02-20 08:05

    How about DateTime.TryParse and DateTime.TryParseExact?

    The first one uses the current cultures date format.

    0 讨论(0)
  • 2021-02-20 08:09

    I would just TryParse the input string:

        private bool ParseDateString()
        {
            var theIncomingParam = Request.Params.Get("__EVENTARGUMENT").ToString(); 
    
            DateTime myDate;
    
            if (DateTime.TryParse(theIncomingParam, CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate))
            {
                int TheMonth = myDate.Month;
                int TheDay = myDate.Day;
                int TheYear = myDate.Year;
    
                // TODO: further processing of the values just read
    
                return true;
            }
            else
            {
                return false;
            }
        }
    
    0 讨论(0)
  • 2021-02-20 08:13

    .NET gives us a datetime.parse

    http://msdn.microsoft.com/en-us/library/1k1skd40.aspx

    and a datetime.tryparse

    http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx

    which both are a good way to parse dates from strings

    0 讨论(0)
  • 2021-02-20 08:20

    Use one of the Parse methods defined on the DateTime structure.

    These will throw an exception if the string is not parseable, so you may want to use one of the TryParse methods instead (not as pretty - they require an out parameter, but are safer):

    DateTime myDate;
    if(DateTime.TryParse(dateString, 
                      CultureInfo.InvariantCulture, 
                      DateTimeStyles.None, 
                      out myDate))
    {
       // Use myDate here, since it parsed successfully
    }
    

    If you know the exact format of the passed in date, you can try using the ParseExact or TryParseExact that take date and time format strings (standard or custom) when trying to parse the date string.

    0 讨论(0)
提交回复
热议问题