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();
Related
I have here a little problem and would like to know where is my mistake and how to correct it.
string preConvDATE = monthCombobox2.Text + " " + datecombobox2.Text + ","+ "0000";
//lets say the comboboxes contain something like this "January 1";
DateTime DT = DateTime.ParseExact(preConvDATE, "MMMM d, yyyy 00:00:00", System.Globalization.CultureInfo.InvariantCulture);
string strDate = DT.ToString("yyyy-mm-dd");
try
{
//code that inserts strDate to a column in Mysql DB
}
catch
{
//msg
}
why "0000" for the year? because i was really planning to store just the month and date, but realized i could just store it as a datetime format with a year, and then at viewing the table i'd just use the Mysql MONTH() and DATE() function concatenated to view the Month and Date i stored from the monthCombobox2 and datecombobox2.
I also tried:
Convert.ToDateTime()
But still won't work.
How do i properly parse MMMM d,yyyy date format so that i could convert it to yyyy-mm-dd again and store it as datetime format in the database?
Thank you so much :)
As I can see, you are using text boxes to catch the value of month and date, instead of that you can use dropdowns which will display the month name but return the values like 01 for January and so on. It will be easy for you to format date formats. You don't want to save year that's okay, instead of setting 0000 you can set the current year. Now the problem with that you will not able to figure out the what exactly day was it (e.g Sunday, Monday and so on).
string preConvDATE = monthCombobox2.Text + "/" + datecombobox2.Text+"/" + DateTime.Now.Year.ToString();
DateTime DT = DateTime.ParseExact(preConvDATE, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string strDate = DT.ToString("yyyy-MM-dd");
I hope this will solve your problem. Happy Coding!
I have two parameters one for date and another for time, and i need date value part and time values part.
My two parameters are below.
// For Date parameter
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
bo.Dateused5 = dt;
// For Time parameter
string Fromtiming = ddl_FromHours.SelectedItem.ToString() + ":" + ddl_FromMinutes.SelectedItem.ToString();
DateTime InterviewTime = Convert.ToDateTime(Fromtiming);//StartTime
bo.Dateused4 = InterviewTime;//InterviewTime
so i need to send mail to the candidate to only date part, should not contain time and time part, should not contain date.
are you looking for this:
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
string mailDate = dt.ToString("dd-MMM-yyyy");// will give 01-jan-1999
string date = dt.ToString("dd-MM-yyyy"); // will give 01-01-1999
You can also try using String.Format()
string mailDate = String.Format("{0:dd-MM-yyyy}", dt); // will give 01-01-1999
You can use ToShortDateString():
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
var date = dt.ToShortDateString();
Note that it uses date format attached to the current thread's culture info.
You would need to use strings rather than dates, so change the type of your variables to string so that
bo.Dateused5 = dt.ToString("dd-MMM-yyyy")
would set Dateused5 to a string of the date component, then
bo.Dateused4 = InterviewTime.ToString("HH:MM");
would set Dateused4 to the time component.
Couldn't test your code but I am very sure there are Functions "DateValue" and "TimeValue" you can make use of.
Something like,
Format(DateValue(any datetime), "dd-MM-yyyy")
gives you Only Date in the specified format. Similar way for TimeValue
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 :)
}
I am trying to convert this e.g. 12/31/2012 format into DateTime, however when I run this code the conversion works but the time is not current. I am looking to convert to DateTime but with the current time:
Example: When I run the below code and enter date: 12/31/2012
I get: 12/31/2012 12:00:00 AM
I am not sure how to get the current time instead of 12:00:00 AM
Console.Write("Enter Current Date: ");
string strMyDate = Console.ReadLine();
DateTime dt = DateTime.Parse(strMyDate);
Console.WriteLine(dt);
Console.ReadKey();
You can extract only the time from DateTime.Now by using the TimeOfDay property and add it to your manually entered date, e.g.
var time = dt.Add(DateTime.Now.TimeOfDay);
As an additional note, I would use DateTime.TryParse instead, as the value entered by the user may not be a parseable date, e.g.
DateTime dt;
var isDate = DateTime.TryParse(strMyDate, out dt);
if(isDate)
{
var time = dt.Add(DateTime.Now.TimeOfDay);
}
DateTime.Now will give you current time. Than combine date portion from first value with time portion from Now to get the result.
Add this to your string:
string strMyDate = Console.ReadLine();
strMyDate = string.Format("{0} {1}",
strMyDate,
DateTime.Now.ToShortTimeString());
Haven't actually compiled this but something like this should work:
DateTime dt = DateTime.Parse("12/31/2012 " + DatTime.Now.TimeOfDay.ToString());
You can build up the time from the hours, minutes and seconds portion of DateTime.Now;
string strMyDate = "12/31/2012";
DateTime dt = DateTime.Parse(strMyDate);
DateTime current = DateTime.Now;
dt = dt.AddHours(current.Hour).AddMinutes(current.Minute).AddSeconds(current.Second);
Console.WriteLine(dt);
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