简体   繁体   中英

Cannot convert 'string' to 'System.DateTime' C# WPF

Firstly, I want to say that I read many questions about similar problem and I couldn't find anything. The difference is that I can't use DateTime.Now property, and I can't choose any specific date .

It is on the user to choose one date from DatePicker

I have tried Convert, Parse, tryParse, but still couldn't solve it... This code will work fine if I use String in my class instead of DateTime , but I need to use DateTime type. Also, I don't want to display time, that's why I have formated like this. Can I get value to string, so I can parse it later?

string chosenDate = datePicker.SelectedDate.GetValueOrDefault().ToString("dd/MM/yyyy"); //error

After that I thought to move value to my object. This is what I did:

newObject = new Classes.MyClass(DateTime.Parse(chosenDate));

I have lost all ideas... Thank you in advance.

EDIT:

Sorry for too little information about problem.

The problem is that I have a DataGrid which has binding on DateTime date (in.cs). I tried this way because it won't show time, but if I apply the following it shows the time in my result as you can see. 2

If MyClass expects a DateTime , you should use the value from the DatePicker 's SelectedDate property. It returns a Nullable<DateTime> that can be converted to a DateTime using the GetValueOrDefault() method:

newObject = new Classes.MyClass(datePicker.SelectedDate.GetValueOrDefault());

If there is no date selected, GetValueOrDefault() will return DateTime.MinValue .

The DatePicker doesn't store the date in any particular format. That's a formatting thing.

It doesn't set the time either. If you however set the time yourself, you could strip it away using the Date property of the Date time:

datePicker.SelectedDate.GetValueOrDefault().Date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM