从表中获取DateTime字段,并在C#

时间:2017-02-22 21:26:04

标签: c# sql-server winforms sql-server-2012

我有一个SQL Server表,其中有一个名为ProductionDate的DateTime字段。该字段的格式为:2015-06-29 00:00:00.000
我有一个C#WinForm应用程序,用这个选择这个日期:

string productionDate = String.Empty;
var prodDate = pallets.Select(r => r.Production_Date);
if (prodDate.Count() == 1)
{
    productionDate = prodDate.First().ToString();
}

现在,这个表单用这一行调用第二个表单:
EditBOL bol = new EditBOL(BOL, Batch, productionDate)

我要做的是,用prodDate值填写第二个表格 这就是表格的样子:
enter image description here

我正在尝试使用调用函数时获得的Year参数填充MonthDayprodDate字段。
这是被调用的函数:

public EditBOL(string BOL, string Batch, string prodDate)
    {
        InitializeComponent();
        txtBOL.Text = BOL;
        txtBatch.Text = Batch;
        //Code to breakdown prodDAte variable comes here!!
    }

我尝试了很多不同的方法。我试过了 1. DateTime.Parse(prodDate, "yyyy-mm-dd", culture)
2. DateTime.Now.ToString("yyyy-MM-dd h:mm tt");
3. DateTime dateVariable = prodDate??DateTime.MinValue
我尝试这一切的原因是,我不想在函数中的dateProd变量上使用substring,因为日期可以是1-1-201510-10-2015。格式不是mm-dd-yyyy 00:00:00.000,而是m-d-yyyy 00:00:00.000
所以,子串似乎是愚蠢的。所以我尝试将字符串转换为datetime变量并执行DatetimeVariable.YearDatetimeVariable.DateDatetimeVariable.Month

编辑1:错过了几行关于如何从表格中选择日期的代码。

2 个答案:

答案 0 :(得分:1)

如果您坚持要解析prodDate

,请尝试此操作
public EditBOL(string BOL, string Batch, string prodDate)
{
        InitializeComponent();
        txtBOL.Text = BOL;
        txtBatch.Text = Batch;
        //Code to breakdown prodDAte variable comes here!!
        string[] tokens = prodDate.Split(' ')[0].Split('-');
        yearTextBox.Text = tokens[0];
        monthTextBox.Text = tokens[1];
        dayTextBox.Text = tokens[2];
}

我更喜欢这种方法:

public EditBOL(string BOL, string Batch, string prodDate)
{
        InitializeComponent();
        txtBOL.Text = BOL;
        txtBatch.Text = Batch;
        //Code to breakdown prodDAte variable comes here!!
        DateTime date = Convert.ToDateTime(prodDate);
        yearTextBox.Text = date.Year.ToString();
        monthTextBox.Text = date.Month.ToString();
        dayTextBox.Text = date.Day.ToString();
}

答案 1 :(得分:1)

您可以使用DateTime.ParseExact()

public EditBOL(string BOL, string Batch, string prodDate)
{
    InitializeComponent();
    txtBOL.Text = BOL;
    txtBatch.Text = Batch;

    string format = "yyyy-M-d h:m:s.fff";
    DateTime dt = DateTime.ParseExact(prodDate, format, CultureInfo.InvariantCulture);

    textBoxYear.Test = dt.Year.ToString();
    textBoxMonth.Test = dt.Month.ToString();
    textBoxDay.Test = dt.Day.ToString();
}