-2

Tell me how to correct the mistake.

I am trying to convert the string to the correct format, but it does not work for me.

Text = "9/21/2004"

 DateTime d1 = DateTime.ParseExact(text.ToString(), "MM/dd/yyyy", null);
 return (T)Convert.ChangeType(text, underlyingType);

The full method:

public static T To<T>(this object text)
        {
            if (text == null) return default(T);
            if (text.Equals(DBNull.Value)) return default(T);
            if (text is string) if (string.IsNullOrWhiteSpace(text as string)) return default(T);

            var type = typeof(T);
            if(type.ToString() == "QuantLib.Date")
            {
                var dt = (DateTime)text;
                QuantLib.Date date = new QuantLib.Date((int)dt.ToOADate());
                return (T)Convert.ChangeType(date, type);
            }

            var underlyingType = Nullable.GetUnderlyingType(type) ?? type;

            DateTime d1 = DateTime.ParseExact(text.ToString(), "dd/MM/yyyy", null);
            return (T)Convert.ChangeType(d1, underlyingType);
        }

        public static T ToDatetime<T>(this QuantLib.Date date)
        {
            DateTime dt = Convert.ToDateTime(date.month() + " " + date.dayOfMonth().ToString() + ", " + date.year().ToString());
            var type = typeof(T);
            if (type == typeof(string))
                return (T)Convert.ChangeType(dt.ToShortDateString(), typeof(T));
            else
                return (T)Convert.ChangeType(dt, typeof(T));
        }
Jared Forth
  • 1,577
  • 6
  • 17
  • 32
  • Does it work if month is 09 rather than 9? – mjwills May 24 '19 at 12:17
  • Possible duplicate of [String was not recognized as a valid DateTime " format dd/MM/yyyy"](https://stackoverflow.com/questions/2193012/string-was-not-recognized-as-a-valid-datetime-format-dd-mm-yyyy) – Anas Alweish May 24 '19 at 12:18
  • 1
    since your month is not `09` but `9` I guess the _exact_ format is `M/d/yyyy` (assuming the 5th day would also be `5` instead of `05`) – René Vogt May 24 '19 at 12:19
  • 1
    Also, you might want to look up what "MM" and "dd" stand for (https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings). The numeral `9` there in your string does not match "MM" –  May 24 '19 at 12:19
  • @VladBondarenko Please delete your question if you are not going to engage with the comments. – mjwills May 27 '19 at 00:25

1 Answers1

0

MM/dd/yyyy is not the correct format for "9/21/2004", M/dd/yyyy is, as you are giving only one digit for the month (M), which precedes the days (dd). I'd suggest you have a look at the official documentation provided by @elgonzo in the comments. M/dd/yyyy still works if you use two digits for the months, as in "12/21/2004".

StackLloyd
  • 409
  • 2
  • 9