Cómo uso DateTime.TryParse con un Nullable?


Quiero usar DateTime.Método TryParse para obtener el valor datetime de una cadena en una Nullable. Pero cuando intento esto:

DateTime? d;
bool success = DateTime.TryParse("some date text", out (DateTime)d);

El compilador me dice

El argumento ' out ' no se clasifica como una variable

No estoy seguro de lo que tengo que hacer aquí. También he intentado:

out (DateTime)d.Value 

Y eso tampoco funciona. Alguna idea?

Author: Alex Jolig, 2008-10-10

7 answers

DateTime? d=null;
DateTime d2;
bool success = DateTime.TryParse("some date text", out d2);
if (success) d=d2;

(Podría haber soluciones más elegantes, pero ¿por qué no simplemente hacer algo como lo anterior?)

 109
Author: Jason Kealey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-31 09:26:32

Como dice Jason, puedes crear una variable del tipo correcto y pasarla. Es posible que desee encapsular en su propio método:

public static DateTime? TryParse(string text)
{
    DateTime date;
    if (DateTime.TryParse(text, out date))
    {
        return date;
    }
    else
    {
        return null;
    }
}

... o si te gusta el operador condicional:

public static DateTime? TryParse(string text)
{
    DateTime date;
    return DateTime.TryParse(text, out date) ? date : (DateTime?) null;
}

O en C # 7:

public static DateTime? TryParse(string text) =>
    DateTime.TryParse(text, out var date) ? date : (DateTime?) null;
 137
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-10 18:24:28

Aquí hay una edición ligeramente concisa de lo que Jason sugirió:

DateTime? d; DateTime dt;
d = DateTime.TryParse(DateTime.Now.ToString(), out dt)? dt : (DateTime?)null;
 19
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-31 21:41:14

No puedes porque Nullable<DateTime> es un tipo diferente a DateTime. Necesita escribir su propia función para hacerlo,

public bool TryParse(string text, out Nullable<DateTime> nDate)
{
    DateTime date;
    bool isParsed = DateTime.TryParse(text, out date);
    if (isParsed)
        nDate = new Nullable<DateTime>(date);
    else
        nDate = new Nullable<DateTime>();
    return isParsed;
}

Espero que esto ayude :)

EDITAR: Eliminado el (obviamente) método de extensión incorrectamente probado, porque (como se señala por algunos malos hoor) métodos de extensión que intentan cambiar el parámetro "este" no funcionará con los Tipos de valor.

P.d. El Bad Hoor en cuestión es un viejo amigo:)

 19
Author: Binary Worrier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-16 15:01:58

¿ Qué hay de crear un método de extensión?

public static class NullableExtensions
{
    public static bool TryParse(this DateTime? dateTime, string dateString, out DateTime? result)
    {
        DateTime tempDate;
        if(! DateTime.TryParse(dateString,out tempDate))
        {
            result = null;
            return false;
        }

        result = tempDate;
        return true;

    }
}
 4
Author: user2687864,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-24 22:06:36

No veo por qué Microsoft no manejó esto. Un pequeño método de utilidad inteligente para lidiar con esto (tuve el problema con int, pero reemplazar int con DateTime será el mismo efecto, podría ser.....

    public static bool NullableValueTryParse(string text, out int? nInt)
    {
        int value;
        if (int.TryParse(text, out value))
        {
            nInt = value;
            return true;
        }
        else
        {
            nInt = null;
            return false;
        }
    }
 1
Author: JStrahl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-12 18:20:09

Alternativamente, si no te preocupa la posible excepción planteada, puedes cambiar TryParse por Parse:

DateTime? d = DateTime.Parse("some valid text");

Aunque tampoco habrá un booleano que indique éxito, podría ser práctico en algunas situaciones en las que sepa que el texto de entrada siempre será válido.

 0
Author: monsieurgutix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-07 19:45:49