Date Time from Multi ComboBoxes - c#

I am trying to combine a DateTime from a number of combo boxes that i have on a form.
From this image you can see how the combo boxes are laid out.
Wondering what is the best way to do this currently i have the following but am not sure that it is correct.
string startdate = cmbMonthYear.Text + "-" + cmbMonth.SelectedIndex.ToString()+ "-" + cmbDay.Text + " "+ "07:00";
DateTime StartDate = DateTime.ParseExact(startdate, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
What is the best way that i could go about this?

A better way would probably be to avoid the parse exact and make sure you have the most accurate representation of the date you want, preferably in integers. You'll want to set the Value-parts of the items in your comboboxes as well. You can probably do that in the code that adds the items to those comboboxes.
So you'll have something like:
// Check your input here
// ...
int day = Convert.ToInt32(cmbDay.SelectedValue);
int month = Convert.ToInt32(cmbMonth.SelectedValue); // No need to have text in SelectedValue, just integer
int year = Convert.ToInt32(cmbMonthYear.SelectedValue);
DateTime StartDate = new DateTime(year, month, day, 7, 0, 0);

This should work (if you're sure about your input):
var date = new DateTime(int.Parse(cmbMonthYear.Text), cmbMonth.SelectedIndex, int.Parse(cmbDay.Text), 7, 0, 0);

Use the DateTime.TryParse method to also validate the input from the user. A good practice when sometimes you have textboxes instead of dropdownlists:
string startdate = cmbMonthYear.SelectedValue
+ "-" + cmbMonth.SelectedValue
+ "-" + cmbDay.SelectedValue
+ " 07:00";
DateTime StartDate;
if(!DateTime.TryParse(startdate, out StartDate){
//invalid date, show a warning message (e.g. lblErrors.Text = "Start Date is not valid!";)
}else{
//your date is parsed and valid :)
}

Related

c# formatting data write to csv files

My C# is very limited and my english too. I need your help. I need to edit the data from the barcode reader. Incoming data like this.
1-) 12345678 (Barcode)
2-) 310319 (Date d m y format)
3-) 174252 (Hour minute second)
4-) 123 (Barcode)
5-) 010419 (Date d m y format)
6-) 153020 (Hour minute second)
7-) 3873 (Code)
Ok this is my data from the barcode reader. I want to format this data as follows.
the final output is sample like this. Sorry for my bad english can you help me please
1-) 12345678 (Barcode not change)
2-) 2 and 3 lines to timestamp ( 310319 + 174252) ? to timestamp
3-) 123 (Barcode not change)
4-) 5 and 6 lines to timestamp (010419 + 153020) ? to timesatamp
5-) 3873 (not change)
string name = lvw.SubItems[1].Text = Splt[0];
string filePath = #"C:\Temp\data.csv";
var one = lvw.SubItems[1].Text = Splt[0];
var two = lvw.SubItems[1].Text = Splt[1];
var three = lvw.SubItems[1].Text = Splt[2];
var four = lvw.SubItems[1].Text = Splt[3];
var five = lvw.SubItems[1].Text = Splt[4];
var six = lvw.SubItems[1].Text = Splt[5];
var seven = lvw.SubItems[1].Text = Splt[6];
var data = one +";" + two + ";" + three + ";"
+ four + ";" + five + ";" + six + ";" + seven + Environment.NewLine;
File.AppendAllText(filePath, data);
variable two + three combine to timestamp this is my problem ?
#Henk Holtermans answer works pretty well with the question you asked, since you didn't determine what a timestamp is in your case.
I'm just gonna answer to add some DateTime usage, since it may be useful for you in the future.
First, convert the strings to a DateTime object:
string date = "310319";
string time = "174252";
DateTime dt;
string timestamp;
bool correct = DateTime.TryParseExact(date + time,
"ddMMyyHHmmss",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal,
out dt);
if(correct){
timestamp = dt.ToString("yyyyMMddHHmmssffff");
}
TryParse lets you get a boolean result of your conversion, meaning that you don't need to check for errors, just ifthe result is true.
TryParseExact lets you tell the function exaclty how is your string formed
Here you can see a list os custom format strings
out dt is where the converted datetime is gonna get stored
After that I'm checking if the result boolean and if the conversion was successful I'm getting a timestamp string of the DateTime object.
"yyyyMMddHHmmssffff" is the output format of the string, where yyyy is the year in 4 chars, MM the month in 2 chars and so on. You have every possible custom string in the link I already provided.
string date = "310319";
string time = "174252";
DateTime dt;
bool correct = DateTime.TryParseExact(date + time,
"ddMMyyHHmmss",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal,
out dt);
Console.WriteLine(dt);
DateTimeOffset dto = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
dto = new DateTimeOffset(dt, TimeSpan.Zero);
long y = dto.ToUnixTimeSeconds();
Console.WriteLine(y); // output 1554054172
thank you to everyone. That's how I solved my problem.

How to find difference for two time values in string?

I am working on a new project in c#, i have no experience with date and time.
Here i need to find the difference between two time values which is in string format
string pointavalue = comboBox1.Text + ":" + comboBox2.Text + ":" + comboBox5.Text;
string pointbvalue = comboBox3.Text + ":" + comboBox4.Text + ":" + comboBox6.Text;
string pointcvalue = comboBox7.Text + ":" + comboBox8.Text + ":" + comboBox9.Text;
DateTime pointa = DateTime.Parse(pointavalue, System.Globalization.CultureInfo.CurrentCulture);
DateTime pointb = DateTime.Parse(pointbvalue, System.Globalization.CultureInfo.CurrentCulture);
DateTime pointc = DateTime.Parse(pointcvalue, System.Globalization.CultureInfo.CurrentCulture);
string time1 = pointa.ToString("HH:mm:ss");
string time2 = pointb.ToString("HH:mm:ss");
string time3 = pointc.ToString("HH:mm:ss");
There is three Values pointavalue, pointbvalue. pointcvalue.
They are combined string values of comboboxes.
Now how do i subtract pointbvalues from pointavalues?
I know they are in string format so operations cannot be performed.
the code you are looking is not mine, someone helped me but its working as a expected.
I am learning C# so bear with me.
ok i think figure out something, but still i can't solve it.
Here is my recent work with the code
DateTime inputa = DateTime.Parse(label21.Text, System.Globalization.CultureInfo.CurrentCulture);
DateTime inputb = DateTime.Parse(label23.Text, System.Globalization.CultureInfo.CurrentCulture);
if (pointa < pointb)
{
TimeSpan diff1 = pointb.Subtract(pointa);
DateTime d1=Convert.ToDateTime(diff1);
if (d1 < inputa)
{
label34.Text = "fail";
}
else
{
label34.Text = "pass";
}
Here i want to check the condition of the time diff1 and inputa, that's it that's all i need to finish this project.
The reason why you can't solve this problem is that you are trying to compare two different data types, Timespan and Datetime are not same
Either convert all your string to "Timespan" (That is better option).
Datetime will give you the present date, but it seems you don't need that.
Last but not least learn some basics before you ask these questions.
One more simple example:
void Main()
{
DateTime now = DateTime.Now;
DateTime yesterday = now.AddDays(-1);
TimeSpan difference = yesterday - now;
Console.WriteLine (difference.GetType().Name);
Console.WriteLine (difference.TotalSeconds); // expecting -86400
}
running this will print
TimeSpan
-86400
Take a look at the DateTime.Substract method:
TimeSpan abdiff = pointb.Substract(pointa);
TimeSpan bcdiff = pointc.Substract(pointb);
Alternatively, you can use the - operator, you get back a Timespan which contains the differences:
TimeSpan abdiff = pointb - pointa;
TimeSpan bcdiff = pointc - pointb;
Assuming that your combo boxes contain the hour, minute, and second then you could do the following.
TimeSpan pointa = new TimeSpan(int.Parse(comboBox1.Text), int.Parse(comboBox2.Text), int.Parse(comboBox5.Text));
TimeSpan pointb = new TimeSpan(int.Parse(comboBox3.Text), int.Parse(comboBox4.Text), int.Parse(comboBox6.Text));
TimeSpan pointc = new TimeSpan(int.Parse(comboBox7.Text), int.Parse(comboBox8.Text), int.Parse(comboBox9.Text));
TimeSpan aTob = pointa > pointb
? pointa - pointb
: (pointa + TimeSpan.FromDays(1)) - pointb;
Basically this assumes that your combo boxes only have valid hour (0-23), minute (0-59), and second (0-59) values. Then you just need to determine if your times are on the same day or not. If you assume that pointa is latter than pointb then checking if it is greater than pointb means you can do a straight subtraction. If not then it must be the time for the next day and you just add 1 day to it before subtracting pointb.
This is based on your assertion that 01:00 - 23:00 should be 2 hours and not -22. Thought it would be best if there where a date included so you would know for sure if the times are on the same day or the next day or from completely different years.

Save two TextBox as DateTime asp.net C#

I have two textBox in first i have Date in this format : 2012.09.20 and in the second i have Time in this format: 15:30:00. In database i have Column name "Eventstart" type: DateTime. Now i like to take the value from two textbox and put them in something like this:
DateTime end = Convert.ToDateTime(TextBoxEnd.Text) + Convert.ToDateTime(TextBoxTimeEnd.Text);
But give me this error : Error 2 Operator '+' cannot be applied to operands of type 'System.DateTime' and 'System.DateTime'
It sounds like you should be using:
DateTime date = Convert.ToDateTime(TextBoxEnd.Text);
DateTime time = Convert.ToDateTime(TextBoxTimeEnd.Text);
DateTime combined = date.Date + time.TimeOfDay;
Or you could combine the text and then parse that:
DateTime dateTime = Convert.ToDateTime(TextBoxEnd.Text + " " +
TextBoxTimeEnd.Text);
I'm not sure I'd use Convert.ToDateTime at all though - if you know the exact format that the textbox will be in, you should use DateTime.TryParseExact. You should work out which culture to use in that case though. If it's a genuinely fixed precise format, CultureInfo.InvariantCulture might be appropriate. If it's a culture-specific format, then use the user's culture.
You might also want to use an alternative UI representation which doesn't use textboxes at all, which would avoid potentially troubling string conversions.
Concatenate your TextBoxes text and use DateTime.ParseExact with format "yyyy.MM.dd HH:mm:ss"
After concatenating the text you should have: "2012.09.20 15:30:00"
DateTime dt = DateTime.ParseExact(TextBoxEnd.Text + " " + TextBoxTimeEnd.Text,
"yyyy.MM.dd HH:mm:ss",
CultureInfo.InvariantCulture);
Have you tried something like
DateTime end = Convert.ToDateTime(TextBoxEnd.Text) + TimeSpan.Parse(TextBoxTimeEnd.Text);
First concatenate both the values and then add it to a DateTime variable
example:
string str = date.Text + time.Text; // assumed date and time are textboxes
DateTime dt=new DateTime();
DateTime.TryParse(str,dt); // returns datetime in dt if it is valid

parsing datetime but dt is changing the day from 8th to 7th?

DateTime dt = DateTime.Parse(value)
Where my value = {3/8/2011 12:00:00 AM}
but dt is showing dt = {3/7/2011 12:00:00 AM}
Please shed some light as I am about to pull my hair.
EDIT: Code OP posted as a comment:
foreach (SPField field in contentType.Fields)
{
string fValue;
object value = spitem[field.Id];
if (value is DateTime)
{
DateTime dateField = DateTime.Parse(field.GetFieldValueAsHtml(value));
DateTime dt = DateTime.Parse(field.GetFieldValueAsText(value), CultureInfo.GetCultureInfo("en-US"));
fValue = dt.ToShortDateString();
lblMetaData.Text += field + ": " + fValue + "\r\n";
}
else
{
fValue = field.GetFieldValueForEdit(value);
lblMetaData.Text += field + ": " + fValue + "\r\n";
}
}
My gut tells me there is a typo in the code. There is probably a missing an assignment.
DateTime dt = DateTime.Parse("3/7/2011 12:00:00 AM");
....
DateTime.Parse("3/8/2011 12:00:00 AM"); //Parse's return is being ignored
....
dt is still {3/7/2011 12:00:00 AM}
Make sure the call to DateTime.Parse("3/8/2011 12:00:00 AM"); is being assigned to dt.
Based on your edit I feel like your code would be better like this, however the posted code should still work.
foreach (SPField field in contentType.Fields)
{
string fValue;
object value = spitem[field.Id];
if (value is DateTime)
{
DateTime dt = (DateTime)value;
fValue = dt.ToShortDateString();
lblMetaData.Text += field + ": " + fValue + "\r\n";
}
else
{
fValue = field.GetFieldValueForEdit(value);
lblMetaData.Text += field + ": " + fValue + "\r\n";
}
}
I can't reproduce your problem. The following code works for me, no change in the day part:
DateTime dt = DateTime.Parse("3/8/2011 12:00:00 AM", CultureInfo.GetCultureInfo("en-US"));
Assert.AreEqual(new DateTime(2011, 3, 8), dt);
Please try to post actual code that reproduces your problem.
UPDATE:
Now that you posted some code, I can say the following:
Your code doesn't seem to make sense. Why?
Because your code will only execute the if clause, if value is a DateTime. But in that case, you first somehow convert it to a text with GetFieldValueAsText and parse that text back into a DateTime. Just use the value directly.
Anyhow, even with that strange code, it should work, if field.GetFieldValueAsText(value) would work correctly, which I doubt it does. Did you check that it indeed returns the correct string?
A DateTime will always have a time, but you don't have to do anything with it. For instance, if you need to display a DateTime back to a user, just don't show the time:
var display = DateTime.Now.ToShortDateString()
The DateTime data type stores both a date and time. There is no way to change this.
If you want to change the way the date appears when you display it, just format it to display only the date. For example, use dt.ToString("D"); or dt.ToShortDateString();.
The DateTime structure represents an instant in time, typically expressed as a date and time of day.
If you want the time portion only you can select
dt.ToShortTimeString();

C#: how do I subtract two dates?

Here's my code:
DateTime date1 = new DateTime(byear, bmonth, bday, 0, 0, 0);
DateTime datenow = DateTime.Now;
DateTime date2 = datenow - date1
On the last line I am getting this error:
Error 1 Cannot implicitly convert type 'System.TimeSpan' to 'System.DateTime'
How do I subtract two dates?
Well the point is that if you think of it, subtracting a date to another should not yield a date, it should yield a time span. And that is what happens when you use DateTime.Subtract().
TimeSpan timeSpan = datenow - date1; //timespan between `datenow` and `date1`
This will make your current code work.
If on the other hand you want to subtract, let's say, one year from your date, you can use:
DateTime oneYearBefore = DateTime.Now.AddYears(-1); //that is, subtracts one year
As already mentioned, date - date gives you a TimeSpan, not a DateTime. If you want a DateTime, use AddDays(-1) as in:
DateTime subtractedDate = date1.AddDays(-1);
The result of a date comparison is a TimeSpan, not a DateTime value.
You want to do this:
TimeSpan result = datenow - date1;
.Subtract has two overloads. One accepts a DateTime and returns a TimeSpan, the other accepts a TimeSpan and returns a DateTime.
In other words, if you subtract a date from a date, you get the timespan difference. Otherwise, if you subtract a timespan from a date, you get a new date.
Can you clarify what you are trying calculate? The difference between any two dates in C# or real life is a time span. If you are trying to calculate age then what you want is the timespan since their birth. Change Date2 to to
Timespan age = datenow - date1;
You are correctly subtracting two dates in your code. What's going on is that you expect the difference between the two dates to be another date, and that's not the case.
As other posters have noticed, you get a TimeSpan. From your variable names I get the sense you're trying to find out someone's age.
Age is not a date, it's a duration. Read up on the TimeSpan object and you will find that it correctly expresses the idea you are looking for.
I'm not 0029-01-01 years old, I'm 29 years old. (Today is not my birthday, but assume it is for easy math.)
If you're trying to show someone's age in a control and that control wants a DateTime you are probably using the wrong control to do it.
Try using ticks...?
DateTime date1 = new DateTime(1986, 3, 16, 0, 0, 0);
DateTime datenow = DateTime.Now;
DateTime date2 = new DateTime(datenow.Subtract(date1).Ticks);
You are expecting the difference of two dates to be a date which is not. That being said, if you need to subtract a certain number of days or months, it can easily be done using the built in methods of the DateTime object such as .AddDays(-1), note that I used a negative number to substract, you can apply the opposite. Here is a quick example.
DateTime now = DateTime.Now;
// Get the date 7 days ago
DateTime sevenDaysAgo = now.AddDays(-7);
// Bulk: Get the date 7 days and two hours ago
DateTime sevenDaysAndtwoHoursAgo = now.Add(-(new TimeSpan(7, 2, 0, 0)));
Use this code:
DateTime? Startdate = cStartDate.GetValue<DateTime>().Date;
DateTime? Enddate = cEndDate.GetValue<DateTime>().Date;
TimeSpan diff = Enddate.GetValue<DateTime>()- Startdate.GetValue<DateTime>() ;
txtDayNo.Text = diff.Days.GetValue<string>();
TimeSpan Example:
private void Form1_Load(object sender, EventArgs e)
{
DateTime startdatetime = new DateTime(2001, 1, 2, 14, 30, 0);
DateTime enddatetime = DateTime.Now;
TimeSpan difference = enddatetime.Subtract(startdatetime);
string sdifference = "TotalDays:" + difference.TotalDays + Environment.NewLine;
sdifference += "TotalHours:" + difference.TotalHours + Environment.NewLine;
sdifference += "TotalMilliseconds:" + difference.TotalMilliseconds + Environment.NewLine;
sdifference += "TotalMinutes:" + difference.TotalMinutes + Environment.NewLine;
sdifference += "TotalSeconds:" + difference.TotalSeconds + Environment.NewLine;
sdifference += "Ticks:" + difference.Ticks + Environment.NewLine;
sdifference += "Total:" + difference.Days + " days, " + difference.Hours + " hours, " + difference.Minutes + " minutes, " + difference.Seconds + " seconds and " + difference.Milliseconds + " milliseconds.";
TextBox TextBox1 = new TextBox();
TextBox1.Multiline = true;
TextBox1.Dock = DockStyle.Fill;
TextBox1.Text = sdifference;
this.Controls.Add(TextBox1);
}
Not exactly an answer to your question, but I prefer using var instead of annotating the variables with types. var IMO makes code look much cleaner than otherwise.
Here's your code snippet with vars:
var date1 = new DateTime(byear, bmonth, bday, 0, 0, 0);
var datenow = DateTime.Now;
var date2 = datenow - date1;
EDIT:
For the C# developers with the var-is-bad mindset:
[ Original Post Here ]
I use var extensively. There has been
criticism that this diminishes the
readability of the code, but no
argument to support that claim.
Admittedly, it may mean that it's not
clear what type we are dealing with.
So what? This is actually the point of
a decoupled design. When dealing with
interfaces, you are emphatically not
interested in the type a variable has.
var takes this much further, true, but
I think that the argument remains the
same from a readability point of view:
The programmer shouldn't actually be
interested in the type of the variable
but rather in what a variable does.
This is why Microsoft also calls type
inference “duck typing.”
So, what does a variable do when I
declare it using var? Easy, it does
whatever IntelliSense tells me it
does. Any reasoning about C# that
ignores the IDE falls short of
reality. In practice, every C# code is
programmed in an IDE that supports
IntelliSense.
If I am using a var declared variable
and get confused what the variable is
there for, there's something
fundamentally wrong with my code. var
is not the cause, it only makes the
symptoms visible. Don't blame the
messenger.
Now, the C# team has released a coding
guideline stating that var should only
be used to capture the result of a
LINQ statement that creates an
anonymous type (because here, we have
no real alternative to var). Well,
screw that. As long as the C# team
doesn't give me a sound argument for
this guideline, I am going to ignore
it because in my professional and
personal opinion, it's pure baloney.
(Sorry; I've got no link to the
guideline in question.)
Actually, there are some
(superficially) good explanations on
why you shouldn't use var but I still
believe they are largely wrong. Take
the example of “searchabililty”: the
author claims that var makes it hard
to search for places where MyType is
used. Right. So do interfaces.
Actually, why would I want to know
where the class is used? I might be
more interested in where it is
instantiated and this will still be
searchable because somewhere its
constructor has to be invoked (even if
this is done indirectly, the type name
has to be mentioned somewhere). -
Konrad Rudolph

Categories