moonwing1988
moonwing1988

Reputation: 33

How to format Datetime? type to "yyyy-MM-dd"

I query some field from database, the Planstartdate is datetime type, and the Planstartdate can be null, I want to format the Planstartdate to "yyyy-MM-dd"

            DataTable dt = ds.Tables[0];
        var query = dt.AsEnumerable()
        .Select(dr =>
        new InitOverview
        {
            IID = string.IsNullOrEmpty(dr.Field<string>("IID").ToString()) ? "" : dr.Field<string>("IID"),
            ProjectName = string.IsNullOrEmpty(dr.Field<string>("ProjectName")) ? "" : dr.Field<string>("ProjectName"),
            TeamLead = string.IsNullOrEmpty(dr.Field<string>("TeamLead")) ? "" : dr.Field<string>("TeamLead"),
            Status = string.IsNullOrEmpty(dr.Field<string>("Status")) ? "" : dr.Field<string>("Status"),
            OverallStatus = string.IsNullOrEmpty(dr.Field<string>("OverallStatus")) ? "" : dr.Field<string>("OverallStatus"),
            Planstartdate = dr.Field<DateTime?>("Planstartdate"),
            Planenddate = dr.Field<DateTime?>("Planenddate"),
            Actualstartdate = dr.Field<DateTime?>("Actualstartdate"),
            Actualenddate = dr.Field<DateTime?>("Actualenddate")
        }
        ).ToList();

anybody can help to realize it? Thanks

Upvotes: 3

Views: 1551

Answers (2)

Karan Desai
Karan Desai

Reputation: 3142

While @mason's answer definitely works, I would like to add that since you are using DataTable, there might be the case that you are fetching dates from Database (and convert it to datatable to print in excel or vice versa), in such case 'HasValue' might not work if database contains DBNull.Value. Therefore, you should also check if the data you are fetching has DBNull.Value or not.

new InitOverview
{
    Planstartdate = dr["PlantStartDate"]!=DBNull.Value ? "Check Null condition mentioned in previous answer" : "no date";
}

Upvotes: 1

mason
mason

Reputation: 32694

Assuming you have a nullable DateTime stored in a variable, you need to check whether it's null or not. Then you can access the underlying value and convert it to a string. Nullable types provide a boolean property HasValue that you should check prior to trying to work with the underlying object.

using System;

public class Program
{
    public static void Main()
    {
        DateTime? actualStartDate = DateTime.Now;

        if(actualStartDate.HasValue)
        {
            string s = actualStartDate.Value.ToString("yyyy-MM-dd");
            Console.WriteLine("value: " + s);
        }       
    }
}

Fiddle here.

If you want to do this within your object initializer, it would look something like this, using a ternary operator:

new InitOverview
{
    Planstartdate = dr.Field<DateTime?>("Planstartdate").HasValue
        ? dr.Field<DateTime?>("Planstartdate").Value.ToString("yyyy-MM-dd") : "no date";
}

Fiddle here.

However, I would caution you that converting it to a string at this point is probably not a good idea. In code, you should generally leave dates as dates until they actually need to be displayed to a user, so you delay it as long as possible. Only in the view layer of your application should you actually convert a date to a string. This keeps the API cleaner (no need to convert it to a date again to manipulate it) and ensures that it's simple to convert to the correct format for display to the user according to their culture settings.

Also, you're doing boring wiring up of database records to .NET objects. It's tedious and a waste of time. You should use a micro ORM such as Dapper and make this much cleaner. It could be:

using (var connection = new SqlConnection(connectionString))
{
    return connection.Query<InitOverview>(selectStatement).AsList();
}

Upvotes: 2

Related Questions