I have a SQL Server table that has a DateTime field called ProductionDate
. The format of this field is: 2015-06-29 00:00:00.000
I have a C# WinForm application that selects this date with this:
string productionDate = String.Empty;
var prodDate = pallets.Select(r => r.Production_Date);
if (prodDate.Count() == 1)
{
productionDate = prodDate.First().ToString();
}
Now, this form calls a second form with this line:
EditBOL bol = new EditBOL(BOL, Batch, productionDate)
What I am trying to do is, fill out the second form with the prodDate
value.
This is what the form looks like:
I am trying to populate the Year
, Month
, and Day
fields using the prodDate
argument it gets when the function is called.
This is the function that gets called:
public EditBOL(string BOL, string Batch, string prodDate)
{
InitializeComponent();
txtBOL.Text = BOL;
txtBatch.Text = Batch;
//Code to breakdown prodDAte variable comes here!!
}
I have tried a lot of different methods. I tried
1. DateTime.Parse(prodDate, "yyyy-mm-dd", culture)
2. DateTime.Now.ToString("yyyy-MM-dd h:mm tt");
3. DateTime dateVariable = prodDate??DateTime.MinValue
The reason I tried all this is, I don't want to use a substring
on the dateProd variable in the function because, the date can either be 1-1-2015
or 10-10-2015
. The format is NOT mm-dd-yyyy 00:00:00.000
, it is md-yyyy 00:00:00.000
So, substring just seems stupid. So I am trying to convert the string to datetime variable and doing DatetimeVariable.Year
, DatetimeVariable.Date
, and DatetimeVariable.Month
.
EDIT 1:Missed a few lines of code on how the date is selected from the table.
Try this if you insist to parse 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];
}
I would prefer this approach:
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();
}
You can just use 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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.