2010-07-27 2 views
1

Date.TryParse가 입력에 매우 관대하다는 것을 알았으므로 언제나 그 값을 반환 할 것입니다. 바닥이 둥글다. 예 :'Date To'기준 필드 사용을위한 자유 텍스트 날짜 필드 반올림

DateTime.TryParse("2010", out testDate) 
-> 01 Jan 2010 

또는

DateTime.TryParse("may 2010", out testDate) 
-> 01 May 2010 
내가 입력하는 사용자에게 날짜를 허용하고 싶습니다

가 검색 상단 날짜 제한으로 사용되는 -에 그것을 얻을 수있는 간단한 방법이 있나요 예 : 반환 : 2010 년 12 월 31 일 '2010'만 입력하면 ...

미리 감사드립니다.

답변

1

이 같은 수 :

string inputDate = "May 2010"; 
int year = 0; 
DateTime date = new DateTime(); 

// Try to parse just by year. 
// Otherwise parse by the input string. 
if (int.TryParse(inputDate, out year)) 
{ 
    date = new DateTime(year, 12, 31); 
} 
else 
{ 
    // Parse the date and set to the last day of the month. 
    if (DateTime.TryParse(inputDate, out date)) 
    { 
     date = date.AddMonths(1).AddMilliseconds(-1); 
    } 
    else 
    { 
     // Throw exception for invalid date? 
    } 
} 
+0

우수 작품. 주 - 다른 모든 기간은 해당 기간이 끝날 때까지 진행되지만 '6 월 3 일'은 6 월 2 일 말까지 반올림됩니다. – Overflew

1

당신이 DateTime.TryParse, 당신은 이런 식으로 뭔가를 할 수 할 수있는 모든 형식을 구문 분석 할 수 있기를 원하는 가정 :

public static bool DateTimeTryParseMax(string dtText, out DateTime testDate) 
    { 
     testDate = DateTime.MinValue; 

     string nFmt = null; 
     foreach (string fmt in System.Globalization.DateTimeFormatInfo.CurrentInfo.GetAllDateTimePatterns().Concat(new string[] {"yyyy", "yy"})) 
     { 
      if (DateTime.TryParseExact(dtText, fmt, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out testDate)) 
      { 
       nFmt = fmt; 
       break; 
      } 
     } 

     if (nFmt == null) 
      return false; 

     nFmt = nFmt.Replace("dddd", "xxxx"); // Remove Day of the week as not helpful 
     if (!nFmt.Contains("M")) testDate = testDate.AddMonths(12).AddMonths(-1); 
     if (!nFmt.Contains("d")) testDate = testDate.AddMonths(1).AddDays(-1); 
     if (!nFmt.Contains("h") & !nFmt.Contains("H")) testDate = testDate.AddDays(1).AddHours(-1); 
     if (!nFmt.Contains("m")) testDate = testDate.AddHours(1).AddMinutes(-1); 
     if (!nFmt.Contains("s")) testDate = testDate.AddMinutes(1).AddSeconds(-1); 

     return true; 
    } 

이는 것 사용자가하지 않은 부품을 최대 값으로 설정하십시오.