简体   繁体   中英

Converting string to DateTime safely

I have a string that came from a Database, but I´m not sure that will be a valid dateTime.

First I´m trying to validate if it´s null,

then if not null I want to safely convert it to DateTime because I´m not sure that a row["a"].ToString will be a valid DateTime

output.limitExpiryDate = row["a"] == DBNull.Value ? DateTime.Now : "something to convert here";

Does anyone have any idea?

You can use DateTime.TryParse :

output.limitExpiryDate = DateTime.Now;
DateTime limitExpiryDate;
if(row["a"] != DBNull.Value && DateTime.TryParse(row.Field<string>("a"), out limitExpiryDate))
    output.limitExpiryDate = limitExpiryDate;

It it was a nullable DateTime column you could use the Field method that supports nullable types:

DateTime? limitExpiryDate = row.Field<DateTime?>("a");
if(limitExpiryDate.HasValue)
    output.limitExpiryDate = limitExpiryDate.Value;
 CultureInfo provider = CultureInfo.InvariantCulture;
  var format = "yyyy-MM-dd";
 output.limitExpiryDate = row["a"] == DBNull.Value ? DateTime.Now : DateTime.ParseExact(row["a"], format, provider);

Something like this:

DateTime date = DateTime.Now;
if (row["a"] != null && row["a"] != DBNull.Value)
{
    if (!DateTime.TryParse(row["a"], out date))
        date = DateTime.Now;
}

output.limitExpiryDate = date;

or you can use TryParseExact and specify format, if you know what datetime format your row["a"] has.

You can use this. It doesnt any problem for any date format. It works for every date format

public static DateTime? ToDateTime(this string value)
{
    if (string.IsNullOrEmpty(value))
    {
        return null;
    }
    return Convert.ToDateTime(value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM