0

I have a textbox from which I am sending date as string in 'MM/dd/yyyy' formate, and when I am assigning that value to nullable datetime property value getting the error as string was not recognized as a valid datetime, I am converting the string as below then also getting the same error

private Tbl_UserDetails GetAnnouncementInformation(Tbl_UserDetails userDetails, Dictionary<string, object> details)
{
  userDetails.JoiningDate = string.IsNullOrEmpty(details["JoiningDate "].ToString()) ?
                            (DateTime?)null : 
                             DateTime.ParseExact(details["JoiningDate "].ToString(),
                             "MM/dd/yyyy", null);

  userDetails.JoiningDate = string.IsNullOrEmpty(details["JoiningDate "].ToString()) ?
                            (DateTime?)null : 
                             DateTime.ParseExact(details["JoiningDate "].ToString(),
                             "MM/dd/yyyy", CultureInfo.InvariantCulture);
}

In both the way I am getting the same error. Please help me in this.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Rocky
  • 4,454
  • 14
  • 64
  • 119
  • 4
    What is the value of `details["JoiningDate "].ToString()` and your `CurrentCulture`? – Soner Gönül Aug 25 '14 at 07:15
  • Did you put a breakpoint and see what the contents of `JoiningDate`? What were the contents? – shree.pat18 Aug 25 '14 at 07:16
  • I am getting "08/25/2014" as string value – Rocky Aug 25 '14 at 07:18
  • @Rocky So, you are saying; `DateTime.ParseExact("08/25/2014", "MM/dd/yyyy", CultureInfo.InvariantCulture)` throws `FormatException`? It doesn't. The problem can be somewhere else? – Soner Gönül Aug 25 '14 at 07:25
  • FYI you don't need to cast as `null` as `DateTime?`, `null` is an acceptable return type for any nullable type. – James Aug 25 '14 at 08:00
  • 1
    Just another reminder what a *terrible* idea it is to store dates as string in a dbase column. – Hans Passant Aug 25 '14 at 08:01
  • Clearly *something* isn't right with your code, however, the example you have given can't match what your code really looks like because the example code/data [works fine](https://dotnetfiddle.net/IEqdCD). – James Aug 25 '14 at 08:33

1 Answers1

3

You could do:

DateTime tempDate;
userDetails.JoiningDate = DateTime.TryParseExact(
  details["JoiningDate "].ToString(), 
  "MM/dd/yyyy", 
  CultureInfo.InvariantCulture, 
  DateTimeStyles.None, 
  out tempDate) 
? tempDate 
: (DateTime?)null;

With extention of :

public static class MyExtensions
{
    public static DateTime? GetNullableDateTime(
        this String str, string format = "MM/dd/yyyy")
    {
        DateTime tempDate;
        var result = DateTime.TryParseExact(str, format, 
            CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDate) 
        ? tempDate 
        : default(DateTime?);
        return result;
    }
}   

It would look like:

userDetails.JoiningDate = 
    details["JoiningDate "].ToString().GetNullableDateTime();

Example program

Assert.IsNull("sddfsdf".GetNullableDateTime());
Assert.IsNotNull("10/20/2014".GetNullableDateTime());
Assert.IsNotNull("20.10.2014".GetNullableDateTime("dd.MM.yyyy"));
Margus
  • 19,694
  • 14
  • 55
  • 103
  • I have used this, but in an extension method. – Margus Aug 25 '14 at 08:12
  • Why do you cast `null` as `(DateTime?)`? Just return `null`. – James Aug 25 '14 at 08:29
  • @James If you have static content checkers they will give an error there. Reason is that **null** does not convey any type information. I am not sure however if **default(DateTime?)** would have intended value. – Margus Aug 25 '14 at 08:35
  • I was going to also suggest `default(DateTime?)` but that ultimately would just return `null`. However, regardless if I used static type checkers I'd say scenarios like these are exceptions to the rule. – James Aug 25 '14 at 08:47
  • I am getting null as return value, not getting the date – Rocky Aug 25 '14 at 08:54
  • What value will **details["JoiningDate "].ToString()** result as? – Margus Aug 25 '14 at 09:02
  • I have "08/22/2014 00:00:00" value in that, which is string type – Rocky Aug 25 '14 at 09:31
  • Well try **.GetNullableDateTime("dd.MM.yyyy HH:mm:ss")** or change default value **string format = "MM/dd/yyyy HH:mm:ss"**. – Margus Aug 25 '14 at 09:34