我有一个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
值填写第二个表格
这就是表格的样子:
我正在尝试使用调用函数时获得的Year
参数填充Month
,Day
和prodDate
字段。
这是被调用的函数:
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-2015
或10-10-2015
。格式不是mm-dd-yyyy 00:00:00.000
,而是m-d-yyyy 00:00:00.000
所以,子串似乎是愚蠢的。所以我尝试将字符串转换为datetime变量并执行DatetimeVariable.Year
,DatetimeVariable.Date
和DatetimeVariable.Month
。
编辑1:错过了几行关于如何从表格中选择日期的代码。
答案 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();
}