I have been going through the motions and still cannot seem to get this right. I have textboxes in a gridview that are populated from an access database. They are all datetime values. In the backend code, I am trying to loop through all those values and then apply conditional formatting. For some unknown reason I am unable to get the value from those textboxes in the gridview and when I do, they are seen by the app as string as opposed to datetime. Converting is futile as the same error, "String was not recognized as a valid DateTime." keeps popping up.
Any ideas on how to get values from a gridview textbox, and then convert them from a string to a datetime format?
Here is the code thus far...
for (int p = 0; p < rowscount; p++)
{
var myLabel2 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label2");
var myLabel4 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label4");
DateTime start = Convert.ToDateTime(myLabel2.Text).Date;
DateTime now = DateTime.Now.Date;
DateTime end = Convert.ToDateTime(myLabel4.Text).Date;
if (now >= start && now <= end)
{
myLabel2.BackColor = Color.Chartreuse;
myLabel4.BackColor = Color.Chartreuse;
myLabel7.BackColor = Color.Chartreuse;
myLabel9.BackColor = Color.Chartreuse;
}
else
{
myLabel2.BackColor = Color.White;
myLabel4.BackColor = Color.White;
myLabel7.BackColor = Color.White;
myLabel9.BackColor = Color.White;
}
}
Thanks in advance
This looks like datetime format issue. Your GridView converts datetime into string in one way and you're trying to convert it back to datetime using different format. Instead of Convert.ToDateTime try using DateTime.ParseExact(String, String, IFormatProvider):
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "dd/MMM/yyyy h:mm tt zzz";
DateTime result = DateTime.ParseExact(dateString, format, provider);
Use format that applies to your case.
Are the textboxes both in the first column of GridView1? For the code:
var myLabel2 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label2");
var myLabel4 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label4");
It means the names of your textboxes are "Label2" and "Label4", and they are both in the first column as you use Cells[0] to fetch them. Your have to make sure of that.
You can add break point to the above code, and debug it. You can see if myLabel2 and myLabel4 have any value.
DateTime date = DateTime.ParseExact(myLabel2.Text, "dd/MM/yyyy", null);
Related
I want to swap two values in a STRING
This is an example of doing it with characters:
string str = "PQRQP";
var res= str.Select(a=> a == 'P' ? 'Q' : (a=='Q' ? 'P' : a)).ToArray();
str = new String(res);
Console.WriteLine(str);
But my string is 2/7/2019, where i want to swap the 2 and 7 each time but as these values are from user input i wont know what they will be before runtime.
Any help appreciated, thanks in advance !
-----------MY SOLUTION----------------
String values = DateRangePicker1.Value.ToString();
String startDate = values.Substring(0, 8);
String endDate = values.Substring(11, 8);
DateTime date = DateTime.ParseExact(startDate, "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime date1 = DateTime.ParseExact(endDate, "M/d/yyyy", CultureInfo.InvariantCulture);
String newSDate = date.ToString();
String newEDate = date1.ToString();
String finalSDate = newSDate.Substring(0, 10);
String finalEDate = newEDate.Substring(0, 10);
I know this is slightly messy, but is working for me without affecting performance
This rather seems to be a localization issue (based on the fact that you are providing a string that looks like a date)
Is it possible that by just providing the correct date annotation that this would solve your problem?
DateTime.ParseExact(string)
for instance is a method that allows you to create a datetime object from a string, if you tell it what the string format is
example:
DateTime date = DateTime.ParseExact("2/1/2019", "M/d/yyyy", CultureInfo.InvariantCulture);
will provide a datetime object set to the first of febuary 2019. You can then convert the datetime object to a string with:
date.ToString("dd-MM-yy");
output: 01-02-19
Edit: if you have a range of acceptable formats, it is possible to provide an array of formats in string form.
You can use split to get the charachters you dont know.
Like this:
var sepratedInput = input.split('/');
var res= sepratedInput[1] +"/"+sepratedInput[0]+"/"+sepratedInput[2];
Console.write(res);
I am having an issue of getting the difference in days between two dates. I will post my code below, but what I am trying to achieve is very simple, just get the difference between 2 dates in days and place the difference in a label.
Code:
string date1 = "";
string date2 = "";
if (myRdr.HasRows)
{
myRdr.Read();
date1 = myRdr["Date 1"].ToString();
date2 = myRdr["Date 2"].ToString();
}
Date 1 and Date 2 are what I am selecting from a query for SQL Server. The date format that I am pulling from my table is 12/25/2015
I have tried these lines to convert the string to date, but it returns nothing:
DateTime date1Diff= DateTime.ParseExact(date1, "dd/MM/yyyy", null);
DateTime date2Diff= DateTime.ParseExact(date2, "dd/MM/yyyy", null);
Then I was planning on getting the difference between date2Diff - date1Diff
So my question is, why are date1Diff and date2Diff returning nothing and what is the best way to get the difference between those two dates?
Put this method in class form or in the same form pass the string date format that you read it gives you date difference
public static double GetDateDiff(string d1, string d2)
{
double result = 0.0;
DateTime MyDate1 = Convert.ToDateTime(d1);
DateTime MyDate2 = Convert.ToDateTime(d2);
result = ((MyDate1 - MyDate2).TotalDays);
return result;
}
Alright, so I have 2 DateTimePickers with custom formats that are set when the form loads,
start.Format = DateTimePickerFormat.Custom;
end.Format = DateTimePickerFormat.Custom;
start.CustomFormat = "dd/MM/yyyy";
end.CustomFormat = "dd/MM/yyyy";
And, my code is supposed to get all weeks between these dates, which it does correctly, then print every week.
I'm managing to do it this way:
DateTimePicker tempdt = start;
tempdt.Format = DateTimePickerFormat.Custom;
tempdt.CustomFormat="dd/MM/yyyy";
int a = getWeeks();//method that gets the weeks between start and end
int d = 0;
for (int i = 0; i < a; i++)
{
d += 7;
MessageBox.Show(tempdt.Value.Date.AddDays(d).ToShortDateString());
}
The code works perfectly, and it does get the weeks precisely, however tempdt still seems to have a "mm/dd/yyyy" format.
Any idea what I might be missing?
The DateTimePickers have nothing to do with this. Your issue is you call ToShortDateString() which for your current culture is set to display as mm/dd/yyyy.
Just use your custom format in the text box too.
MessageBox.Show(tempdt.Value.Date.AddDays(d).ToString("dd/MM/yyyy"));
Also from the code you have shown tempdt is completely unnecessary and it is never even shown to the user. You can also remove the Date call as you don't display the time anyway to the user and are only adding whole number days to the date. This lets you simplify your code to
int a = getWeeks();//method that gets the weeks between start and end
int d = 0;
for (int i = 0; i < a; i++)
{
d += 7;
MessageBox.Show(start.Value.AddDays(d).ToString("dd/MM/yyyy"));
}
The point of the format of a DateTimePicker is to control what the user sees in the control. That 'tempdt' is not even being shown to the user at all so should not be being used at all. Your calculations are using the Value property of that DTP. That property is a DateTime and is completely unaware and unaffected by the format of the DTP. Get rid of the DTP in the calculation and just use a DateTime.
When you display the results of the calculation, you have to convert that DateTime to a String in the appropriate format at that time. If you want to display "dd/MM/yyyy" format then call .ToString("dd/MM/yyyy") rather than .ToShortDateString() because the latter will use the default system format.
I have a textbox and i would love it to be formatted. fortunately for me, i can get this done by changing the textmode = DateTimeLocal. Exactly what I want. Additionally, I would like to load this textbox with default values rather than leaving it with dd/mm/yy __:__:__ . I can change the text if it is a regular textbox (single mode) or even a datetime textbox. but i cannot change it with DateTimeLocal mode. some help please. thank you.
You will have to format the DateTime to a valid Date and Time string that can be parsed, here is one that works:
txtDateTimeLocal.Text = DateTime.Now.ToLocalTime().ToString("yyyy-MM-ddTHH:mm");
For more details on what other attributes you can set, see: http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#local-date-and-time-state-(type=datetime-local)
Try setting the whole datetime format including seconds and milliseconds, worked for me.
txtStartTime.Text = DateTime.Today.ToString("yyyy-MM-ddTHH:mm:ss.ss");
If you want to set a TextBox's DateTime dynamically from a database then you can use this code:
DataTable dtTemp = (DataTable)ViewState["DataSet"]; // this are temporary table
TextBox txtFromDate = (TextBox)gridEditBloackHomework.Rows[e.NewEditIndex].FindControl("txtFromDate");
TextBox txtToDate = (TextBox)gridEditBloackHomework.Rows[e.NewEditIndex].FindControl("txtToDate");
string c = dtTemp.Rows[e.NewEditIndex]["FromDate"].ToString();
DateTime FromDate = Convert.ToDateTime(dtTemp.Rows[e.NewEditIndex]["FromDate"]);
DateTime ToDate = Convert.ToDateTime(dtTemp.Rows[e.NewEditIndex]["ToDate"]);
DateTime dtFromDate = FromDate.AddHours(-2);
DateTime dtToDate = ToDate.AddHours(-2);
txtFromDate.Text = dtFromDate.ToLocalTime().ToString("yyyy-MM-ddTHH:mm").ToString();
txtToDate.Text = dtToDate.ToLocalTime().ToString("yyyy-MM-ddTHH:mm");
My Question is that, I want to find the highest DateTime from a list of DateTime?
I have one Array suppose string[] btime = new string[100];
In that Array I am storing the Date which is coming from the SQL-Server
The SQL Query is [CONVERT(varchar(10),GETDATE(),101)] it is returning the Date in format of MM/dd/yyyy
and then after I am concatenating the Date with my own given Time
i.e .btime[j] = SqlServerDate + " " + 15:20; and so on;
Now, from this given Array I want to find highest Date and Time
So, I have use this logic
string large=""
large=btime[0];
for (int i = 0; i < j; i++)
{
if (DateTime.Compare(DateTime.Parse(btime[i]),DateTime.Parse(large)) > 0)
{
large = btime[i];
}
}
but I am getting the Error at
if(DateTime.Compare(DateTime.Parse(btime[i]),DateTime.Parse(large)) > 0)
The Error is String not recognized as valid DateTime This error is occurring because of my System DateTime Format is yyyy/dd/MM
So Plz any one can help me in solving this problem
I don't want to change format of the system
Others have suggested different ways of parsing the DateTime. This seems pointless to me - if you can possibly change the query, just avoid performing the conversion to a string in the first place. The fewer conversions you use, the fewer chances you have for this sort of thing to be a problem.
Change the query so you end up with DateTime values, and then finding the latest one is trivial in LINQ:
DateTime latest = dateTimes.Max();
Hum,
// Containing your datetime field
string[] btime = new string[100];
var max = btime.Select(s => DateTime.Parse(s, "MM/dd/yyyy", CultureInfo.InvariantCulture)).Max();
Use the DateTime.ParseExact Method.
Example:
CultureProvider provider = CultureInfo.InvariantCulture;
DateTime.ParseExact(btime[i], "yyyy/dd/MM", provider);
you, can use DateTime.ParseExact() functionality to do this. Refer the following code part.
CurDate = DateTime.ParseExact(Name3, "yyyyMMddhhmmssffff", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
You can use the DateTime.ParseExact() method.
CultureProvider provider = CultureInfo.InvariantCulture;
DateTime.ParseExact(btime[i], "MM/dd/yyyy HH:mm", provider);
The second parameter there is the format string. This specifies how your date will be formatted.
Since you are adding a 24 hour time at the end you need the HH:mm (HH says expect a 24 hour time).
Thanks to everyone.
I have got some sort of answer:
string large = "";
large = btime[0];
IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;
// This Code will convert the System Format in Thread, Not the Actual Format
// of The System
CultureInfo ciNewFormat = new CultureInfo(CultureInfo.CurrentCulture.ToString());
ciNewFormat.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
System.Threading.Thread.CurrentThread.CurrentCulture = ciNewFormat;
for (int i = 0; i < TimeBackupCounter; i++)
{
if (DateTime.Compare(DateTime.Parse(btime[i]),DateTime.Parse(large)) > 0)
{
large = btime[i];
}
}