I am attempting to add a Convert funtion to my XAML/C# application. However, the "value" object in the code below is presenting the data back as "2014-12-14", which is generating a runtime error, "Specified cast is not valid". Can anyone help me with the converstion string? I tried ParseExact, but with no success.

      public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                DateTime date = (DateTime)value;
                return date.ToShortDateString();

            }
            catch (Exception ex)
            {
                return DateTimeOffset.MinValue;
            }

        }

I had a similar problem a couple of weeks ago and this was my solution

DateTime.ParseExact(value.Substring(0, 10), "dd/mm/yyyy", null).Date.ToShortDateString();

You should just have to change the format string ("dd/mm/yyyy") to "yyyy/mm/dd".

Hope this helps...

Edited 2 Years Ago by ChrisHunter

That's great thank you Chris. Unfortunately, it doesn't like the .Substring command.

Try value.ToString().Substring(0, 10). If the object passed in as value param isn't a string it won't work. What will you pass in as value param?

You might also need to change the string format to include - instead of /.

Could you mark this thread as solved please? That way people with the same problem will know this thread may contain the solution they're looking for.

Cheers.

This article has been dead for over six months. Start a new discussion instead.