datetime converter WPF

2019-07-23 03:08发布

I have this converter that i made to get the current time once the date is selected from the DataPicker. In string Date i am getting the value that was selected from the DatePicker, but i cant seem to only get the date. The format that is coming into the Value property is 9/24/2013 12:00:00 I would like it to be 9/24/2013

the error i am getting is "Error 122 No overload for method 'ToString' takes 1 argument"

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
            if (value is DateTime)
            {
            string date = value.ToString("d/M/yyyy");
            return (date);
            }

             return string.Empty;
}

5条回答
smile是对你的礼貌
2楼-- · 2019-07-23 03:43

You need to cast it to DateTime first:

public object Convert(object value, Type targetType, object parameter,
                      System.Globalization.CultureInfo culture)
{
    if (value is DateTime)
    {
        DateTime test = (DateTime) value;
        string date = test.ToString("d/M/yyyy");
        return date;
    }

    return string.Empty;
}
查看更多
Animai°情兽
3楼-- · 2019-07-23 03:45

After check on type of value you need cast it to appropriate type, to be able to perform "ToString" call with format parameter. Try:

if (value is DateTime)
{
    var dateValue = value as DateTime;
    string date = dateValue.ToString("dd/MM/yyyy");
    return date; 
}
查看更多
孤傲高冷的网名
4楼-- · 2019-07-23 03:45
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    if (value is DateTime)
    {
        string date=value.Date.ToShortDateString();
        return (date);
    }

    return string.Empty;
}
查看更多
做自己的国王
5楼-- · 2019-07-23 03:47

If you are using a Converter on a WPF DatePicker control, you should note that the WPF DatePicker will itself reformat the date despite the converter that you use. You will have to style the Datepicker to include a StringFormat.

There is a related question here: how to show just Month Year string format in a DatePicker which shows an attached property to modify the behaviour of DatePicker to display a custom format. This is needed because of a deficiency in the WPF Datepicker control itself.

Also note there are some caveats, notably the DatePicker will flicker between its default stringformat and the one you apply! I answered in the above question a workaround for to apply a custom Format to WPF Datepicker without the flicker.

Hope you find the solution you are looking for.

查看更多
We Are One
6楼-- · 2019-07-23 03:51

You should cast value to DateTime type, because there is not a ToString(String f) method for the type of Object.

if (value is DateTime)
{
   var dateTime = (DateTime)value;
   return dateTime.ToString("dd/MM/yyyy");
}

return string.Empty;
查看更多
登录 后发表回答