Windows Forms DateTimePicker 컨트롤에서 날짜 값만 가져 오는 방법은 무엇입니까?
C # 코드로 응용 프로그램을 만들고 있습니다. 컨트롤
에서 날짜 값만 가져 오려면 어떻게합니까 DateTimePicker
?
나는 당신이 winforms 응용 프로그램에서 datetime 선택기를 의미한다고 가정하고 있습니다.
코드에서 다음을 수행 할 수 있습니다.
string theDate = dateTimePicker1.Value.ToShortDateString();
또는 날짜 형식을 지정하려는 경우 :
string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");
DateTime dt = this.dateTimePicker1.Value.Date;
데이터베이스에 날짜 데이터를 삽입 할 때이 문제가 발생했습니다. 간단히 구조체 멤버를 별도로 사용할 수 있습니다. 제 경우에는 SQL 문장에 올바른 값이 있어야하고 슬래시 나 대시 만 추가하면 형식이 완성되므로 유용합니다. , 변환이 필요하지 않습니다.
DateTimePicker dtp = new DateTimePicker();
String sql = "insert into table values(" + dtp.Value.Date.Year + "/" +
dtp.Value.Date.Month + "/" + dtp.Value.Date.Day + ");";
그렇게하면 시간없이 데이트 멤버 만 얻을 수 있습니다 ...
string shortDate = dateTimePicker1.Value.ToShortDateString();
시간 구성 요소없이 날짜를 얻는 방법을 의미합니까? DateTimePicker.Value.Date를 사용합니다. 그러나 필요에 따라 출력 형식을 지정해야합니다.
@Shoban 질문에 C # 태그가 지정되어 있으므로 여기에 적절한 http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.value.aspx가 있습니다.
public MyClass()
{
// Create a new DateTimePicker
DateTimePicker dateTimePicker1 = new DateTimePicker();
Controls.Add(dateTimePicker1);
MessageBox.Show(dateTimePicker1.Value.ToString());
dateTimePicker1.Value = DateTime.Now.AddDays(1);
MessageBox.Show(dateTimePicker1.Value.ToString());
}
이 질문에 이미 좋은 대답이 주어지면 WinForms에서 Vivek가 말한 것처럼 사용자 지정 형식 을 DateTimePicker 형식 속성으로 설정할 수도 있습니다 .이를 통해 DateTimePicker 내의 지정된 형식 문자열에 날짜 / 시간을 표시 할 수 있습니다 . TextBox 에서 텍스트를 얻는 것처럼 간단 합니다.
// Set the Format type and the CustomFormat string.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "yyyy/MM/dd";
이제 DateTimePicker 에서 텍스트를 가져 와서 만 쉽게 Date를 가져올 수 있습니다 .
MessageBox.Show("Selected Date: " + dateTimePicker1.Text, "DateTimePicker", MessageBoxButtons.OK, MessageBoxIcon.Information);
참고 :에 날짜에만 데이터를 삽입하려는 경우 날짜 SQL의 열 유형이 참조 문서 에 대해 지원되는 문자열 리터럴 형식에 관련된 일을 . 지원되지 않으므로 형식 문자열 ydm에 날짜를 삽입 할 수 없습니다 .
dateTimePicker1.CustomFormat = "yyyy/dd/MM";
var qr = "INSERT INTO tbl VALUES (@dtp)";
using (var insertCommand = new SqlCommand..
{
try
{
insertCommand.Parameters.AddWithValue("@dtp", dateTimePicker1.Text);
con.Open();
insertCommand.ExecuteScalar();
}
catch (Exception ex)
{
MessageBox.Show("Exception message: " + ex.Message, "DateTimePicker", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
위 코드는 다음 예외로 끝납니다.
주의하십시오. 건배.
이 시도
var store = dtpDateTimePicker.Value.Date;
store는 엔티티 객체 등 무엇이든 될 수 있습니다.
Datum = DateTime.Parse(DateTimePicker1.Value.ToString("dd/MM/yyyy"))
'Program Tip' 카테고리의 다른 글
OWIN HttpListener를 찾을 수 없습니다. (0) | 2020.11.03 |
---|---|
Pandas 및 matplotlib를 사용하여 범주 형 데이터 플로팅 (0) | 2020.11.03 |
jquery를 사용하여 모든 이벤트를 바인딩 해제하는 방법 (0) | 2020.11.03 |
tools.jar을 찾을 수 없습니다. (0) | 2020.11.03 |
git 태그의 시간과 날짜 가져 오기 (0) | 2020.11.03 |