선택한 콤보 상자 항목에서 반환되는 값 (날짜)이 있습니다. 이 값을 적절한 DateTime 문자열로 변환하고 싶습니다. 문제는 combobox.selectedItem에서 변환 할 문자열입니다.
July 2016
그리고 나는 그것을 (항상 월의 시작)으로 변환하고 싶습니다.
01/07/2016 12:00AM
C #에서 할 일이 없습니까?
그 주위의 유일한 방법은 내가 생각할 수있는 일을하는 것입니다.
if(combobox.selectedItem.Contains("July") && combobox.selectedItem.Contains("2016")) {
//startDate = Set date to 01/07/2016..
endDate = DateTime.Now().ToString();
}
전혀 이상적이지 않습니다 ... 특히 지난 24 개월 이상을 원할 경우 (콤보 상자가 xml 파일의 두 날짜 사이에 매월 채워지기 때문에)
편집 / 업데이트
BOB의 조언에 따라 아래 작업 코드를 참조하십시오!
#region try set Date from selected background populated Month
try
{
//param/arg from backgroundWorker
string selectedDate = filterByMonthComboBoxParam;
//Could also be from direct combobox.selecteditem with system string removed
//string selectedDate = filterByMonthComboBox.SelectedItem.ToString().Replace("System.Windows.Controls.ComboBoxItem:", "");
for (int ifilterByMonthComboBox = 0; ifilterByMonthComboBox < filterByMonthComboBox.Items.Count; ifilterByMonthComboBox++)
{
string _filterByMonthComboBox = filterByMonthComboBox.Items[ifilterByMonthComboBox].ToString();
if (_filterByMonthComboBox.Contains(selectedDate)){
DateTime dtX;
if (DateTime.TryParseExact(selectedDate, "MMMM yyyy", null, DateTimeStyles.AllowWhiteSpaces, out dtX))
{
// Parse success
Console.WriteLine(dtX);
checkMinDate = dtX.ToString();
checkMaxDate = nowTime.ToString();
Console.WriteLine("Date Filter is:");
Console.WriteLine("Min: " + checkMinDate);
Console.WriteLine("Max: " + checkMaxDate);
}
else
{
// parse failed
Console.WriteLine("Failed");
}
}
}
}catch(Exception dateError){
Console.WriteLine(dateError);
}
#endregion try set Date from selected background populated Month
DateTime dt;
if (DateTime.TryParseExact("July 2016", "MMMM yyyy", null, DateTimeStyles.None, out dt))
{
// Parse success
Console.WriteLine(dt);
}
else
{
// parse failed
Console.WriteLine("Failed");
}
결제 DateTime.TryParseExact()
및 형식
편집하다:
날짜에 공백이 있으면 그 string.Trim()
위에 사용 하거나 다음 DateTimeStyles.None
으로 변경하십시오 .DateTimeStyles.AllowWhiteSpaces
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다