2

I have a variable as property like this:

DateTime? something;
something  = Convert.ToDateTime(d1);

where d1 = '04/20/2020 12:50 PM';

I get a runtime error:

String was not recognized as a valid datetime

Then I tried this code:

something  = DateTime.TryParseExact(d1, "MM/dd/yyyy HH:mm tt", null);

and get a compile time error:

No overload for method 'TryParseExact' takes 3 arguments

Then I tried to convert it like by below too

something  = DateTime.TryParseExact(d1, "MM/dd/yyyy HH:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt);

and got another compile-time error:

Cannot implicitly convert type bool to System.DateTime?

How to convert nullable datetime to getting datetime format?

enter image description here

Community
  • 1
  • 1
abbas ahmed
  • 283
  • 2
  • 13
  • See [this](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparseexact?view=netframework-4.8) – Hamid Reza Mohammadi Apr 18 '20 at 19:35
  • 1
    Does this answer your question? [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) – Pavel Anikhouski Apr 18 '20 at 19:37
  • @Hamid Reza Mohammadi its not working...saying 3 parametrised methode not available – abbas ahmed Apr 18 '20 at 19:47

3 Answers3

2

See this

public static bool TryParseExact (string s, string format, IFormatProvider provider, System.Globalization.DateTimeStyles style, out DateTime result);

Parameters

s String A string containing a date and time to convert.

format String The required format of s.

provider IFormatProvider An object that supplies culture-specific formatting information about s.

style DateTimeStyles A bitwise combination of one or more enumeration values that indicate the permitted format of s.

result DateTime When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if either the s or format parameter is null, is an empty string, or does not contain a date and time that correspond to the pattern specified in format. This parameter is passed uninitialized.

Returns Boolean true if s was converted successfully; otherwise, false.

Exceptions ArgumentException styles is not a valid DateTimeStyles value.

-or-

styles contains an invalid combination of DateTimeStyles values (for example, both AssumeLocal and AssumeUniversal).

So we need to check the success or fail, and handle it.

DateTime? something;
if(DateTime.TryParseExact(d1, "MM/dd/yyyy HH:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt))
    something = dt;
else
    something = null;
1

TryParseExact return a bool, yout datetime object is dt

public static void Main()
    {
        string d1 = "04/20/2020 12:50 PM";

        var result  = DateTime.TryParseExact(d1, "MM/dd/yyyy HH:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt);

        Console.WriteLine(dt);

    }
krlosmederos
  • 176
  • 3
  • 11
  • Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. Parser Error Message: The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" could not be located. – abbas ahmed Apr 18 '20 at 19:44
1

This is the correct use of TryParseExact

public static void Main()
{
    string d1 = "04/20/2020 12:50 PM";

    if (DateTime.TryParseExact(d1, "MM/dd/yyyy HH:mm tt", 
        CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt));

        Console.WriteLine("Date time OK: " + dt);
    else
        Console.WriteLine("Invalid Date time: " + d1);
}
T.S.
  • 18,195
  • 11
  • 58
  • 78
  • how could save it in db then? – abbas ahmed Apr 18 '20 at 19:56
  • @abbasahmed There is nothing in your question about saving to DB. But you can do this as Hamid Reza shows - `DateTime dbVal? = null; if (tryparse(....)) dbVal = dt;` 3 Lines of code and now your `dbVal` is ready for saving – T.S. Apr 18 '20 at 20:00
  • I updated with image please check it, getting that error after I updated as u mentioned. – abbas ahmed Apr 18 '20 at 20:06
  • 2
    Just remove that whole `system.codedom` section. Do you compile your code manually? – T.S. Apr 18 '20 at 20:13
  • @abbasahmed What does it mean "as usual". ? How do you run your app? Remove from config file in your app. Probably web.config – T.S. Apr 18 '20 at 20:16
  • 1
    @abbasahmed great. Find web.config in your app and remove this setting – T.S. Apr 18 '20 at 20:19
  • Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: Could not load type 'AppThereCRM_V2.MvcApplication'. Source Error: Line 1: <%@ Application Codebehind="Global.asax.cs" Inherits="AppThereCRM_V2.MvcApplication" Language="C#" %> – abbas ahmed Apr 18 '20 at 20:21
  • 2
    @abbasahmed right-click on your solution and click `Rebuild`. Or do same in the build menu – T.S. Apr 18 '20 at 20:24
  • 1
    Also check [this](https://forums.asp.net/t/2119455.aspx?Error+when+running+a+localhost+site) – Hamid Reza Mohammadi Apr 18 '20 at 20:28