简体   繁体   English

如何格式化日期时间? 输入“yyyy-MM-dd”

[英]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" 我从数据库查询一些字段,Planstartdate是datetime类型,Planstartdate可以为null,我想将Planstartdate格式化为“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 谢谢

Assuming you have a nullable DateTime stored in a variable, you need to check whether it's null or not. 假设您在变量中存储了可以为空的DateTime,则需要检查它是否为null。 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. Nullable类型提供了一个布尔属性HasValue ,您应该在尝试使用底层对象之前进行检查。

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. 这使API更加清洁(无需再次将其转换为日期来操作它)并确保根据文化设置将其转换为正确的格式以便显示给用户。

Also, you're doing boring wiring up of database records to .NET objects. 此外,您正在无聊地将数据库记录连接到.NET对象。 It's tedious and a waste of time. 这很乏味,浪费时间。 You should use a micro ORM such as Dapper and make this much cleaner. 你应该使用微型ORM,如Dapper ,使其更清洁。 It could be: 它可能是:

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

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 . 虽然@mason的答案肯定有效,但我想补充一点,因为您使用的是DataTable,可能会出现这样的情况:您从数据库中获取日期(并将其转换为数据表以在Excel中打印,反之亦然),在这种情况下如果数据库包含DBNull.Value则HasValue可能不起作用。 Therefore, you should also check if the data you are fetching has DBNull.Value or not. 因此,您还应该检查您提取的数据是否具有DBNull.Value

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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