我似乎无法使用 C# 将可为空的日期时间格式化为 "yyyy-mm-dd"

I can't seem to get my nullable datetime formatted to "yyyy-mm-dd" using C#

我正在尝试生成一个 XML 文件,它与我直接从数据库 table 中提取的日期一起使用。 "mm-dd-yyyy"。 但是我似乎无法将其格式化为所需的 "yyyy-mm-dd".

我一直被告知 "No overload for method 'ToString()' takes 1 arguments"。

它在 "new XElement" 内或之前不起作用:

XElement samplecollectionenddate = new XElement(EN + "SampleCollectionEndDate", samp.SampDate.ToString("yyyy-mm-dd"));

我查看了整个 Whosebug,看到了所有这些美妙的字符串格式,但我无法在我的 .ToString() 括号内放入任何内容。

这是我用示例填充的 IEnumerable。

IEnumerable<EDI_RAW_TCR> samples = from c in dc.EDI_RAW_TCRs
       where c.Batch_ID == 20830
       where c.LabID == raw.LabID
       orderby c.Raw_ID
       select c;

foreach (EDI_RAW_TCR samp in samples)
{

以防万一我错过了图书馆,这是我的 class:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Data.Linq;

这似乎有效。

string dt = String.Format("{0:yyyy-MM-dd}", samp.SampDate);

XElement samplecollectionenddate = new XElement(EN + "SampleCollectionEndDate", dt);

可空类型可以表示其基础值类型的正确值范围,以及一个额外的空值。

if( samp.SampDate != null )    
{
    XElement samplecollectionenddate = new XElement(EN + "SampleCollectionEndDate", samp.SampDate.Value.ToString("yyyy'-'mm'-'dd")); 
}

https://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx