DateTimePicker screws up the format c# - c#

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.

Related

Datetime filter in kendo grid

My code is in C# .NET
I am using Kendo Grid version 2013.2.716.340 and server binding to show data in grid.
In Kendo UI Grid, I have a dateTime column but the column filter input only has a date picker but no time picker. Due to this if I select the option IsEqualTo and give a date then I get zero results as the time is set to 00:00:00 in the filter but the columns have some time value.
I want to add time picker along with date picker.
I tried to do this on my column, but it didn't work:
columns.Bound(o => o.Time).Title("Time").Format("{0:MM/dd/yyyy HH:mm:ss}").Filterable(f => f.UI("DateTimeFilter")).Width("5%");
And have applied below script :
<script type="text/javascript">
function DateTimeFilter(control)
{
$(control).kendoDateTimePicker();
}
</script>
The above code works when I select exact datetime from datetimepicker but it doesn't work when I select isequalto.
For eg : If I have this datetime "12/21/2013 07:15:45" displayed in my kendo grid column and when I copy this datetime to isequalto option under filter it does not gives any data.
Also I tried the example provided on this link It also didn't work in my case. Example on this link uses Ajax binding. I need to apply it in case of server binding.
This is an attached image that shows what I want to apply. Here is the link for image.
If I copy the datetime shown in grid to the filter It should filter correctly and give result.
I will be very thankful if anybody could help me out in solving my issue. Thanks in advance.
From my experience, the kendoDateTimePicker is really picky; if the format of the filter cannot specify the datetime precision of the column data, it will not find it.
In your case, your column format is "MM/dd/yyyy HH:mm:ss" (with seconds). The default format for the kendoDateTimePicker is "MM/dd/yyyy h:mm tt" (without seconds and hour spec is mismatched). Since you initialized a default kendoDateTimePicker, no matter what you put in the picker, you could never filter to a date that IS EQUAL TO a column value since you couldn't input how many seconds it was.
The easiest way to ensure it works is to use the same format for both column and the kendoDateTimePicker . Replace your DateTimeFilter function with this:
function DateTimeFilter(control)
{
$(control).kendoDateTimePicker({
format: "MM/dd/yyyy HH:mm:ss",
timeFormat: "HH:mm:ss"
});
}
With regards to the kendoDateTimePicker:
format defines the input value format for control
timeFormat defines the time format of the time picker
interval (didn't use it above), but it specifies the time interval in minutes between each option of the time picker.
I am not using asp.net mvc, so I'm not 100% sure if this solves your problem. However I am certain it will clear up at least some of the filtering issues you have. I can provide a jsfiddle for a purely html/javascript sample if you want.
I know I am late with this answer, but it might still help someone.
The above code works when I select exact datetime from datetimepicker but it doesn't work when I select isequalto. For eg : If I have this datetime "12/21/2013 07:15:45" displayed in my kendo grid column and when I copy this datetime to isequalto option under filter it does not gives any data.
I guess you are experiencing this because your server-side DateTime values contain fractional second data as well and the equals operator does not ignore them at comparison. I have found it easier to come up with a server-side solution instead of writing all sort of dirty JS workarounds.
The idea is that whenever you find a filter in the DataSourceRequest object that would filter on a DateTime property, you manually replace it with a CompositeFilterDescriptor, which truncates the value to the desired precision, sets it as the lower bound and then adds one unit of the desired precision (sec, min, hour, etc.) and sets it as the upper bound.
The code is the following:
public static class KendoHelpers
{
public enum DateTimePrecision
{
Seconds = 1,
Minutes = 2,
Hours = 4
}
public static DataSourceRequest NormalizeDateFilters(this DataSourceRequest request, DateTimePrecision precision)
{
// TODO: Add parameter validation.
for (int i = 0; i < request.Filters.Count; ++i)
{
FilterDescriptor filter = request.Filters[i] as FilterDescriptor;
if (filter != null && filter.ConvertedValue is DateTime && filter.Operator == FilterOperator.IsEqualTo)
{
DateTime val = (DateTime)filter.ConvertedValue;
CompositeFilterDescriptor newFilter = new CompositeFilterDescriptor
{
LogicalOperator = FilterCompositionLogicalOperator.And
};
DateTime lowerBound;
DateTime upperBound;
if (precision == DateTimePrecision.Seconds)
{
lowerBound = val.TruncateToWholeSeconds();
upperBound = lowerBound.AddSeconds(1);
}
else if (precision == DateTimePrecision.Minutes)
{
lowerBound = val.TruncateToWholeMinutes();
upperBound = lowerBound.AddMinutes(1);
}
else if (precision == DateTimePrecision.Hours)
{
lowerBound = val.TruncateToWholeHours();
upperBound = lowerBound.AddHours(1);
}
else
{
// If someone would be stupid enough to supply Hours | Minutes
throw new ArgumentException("Not supported precision. Only Second, Minute, Hour values are supported.", "precision");
}
newFilter.FilterDescriptors.Add(new FilterDescriptor
{
Member = filter.Member,
MemberType = filter.MemberType,
Operator = FilterOperator.IsGreaterThanOrEqualTo,
Value = lowerBound
});
newFilter.FilterDescriptors.Add(new FilterDescriptor
{
Member = filter.Member,
MemberType = filter.MemberType,
Operator = FilterOperator.IsLessThan,
Value = upperBound
});
request.Filters[i] = newFilter;
}
}
return request;
}
}
Remarks:
The DateTime truncater extension is based on this answer.
This method will only do anything if the operator is equals, because if you select Is later than or the like, the default behavior will work just as well.
This method does not care about any present CompositeFilterDescriptors becasue an expression dateToSearch = 2016-11-21 11:22:00 AND dateToSearch = 2016-11-21 11:59:00 makes no sense anyway.
Similar thing could be done for DateTimeOffset values.
An enhancement to Balázs' answer, this assumes that you are using a simple date portion of DateTime and don't care about the time portion at all. It is also recursive to handle being filtered with other unrelated filters.
public static IList<IFilterDescriptor> NormalizeDateFilters(this IList<IFilterDescriptor> filters)
{
for (var i = 0; i < filters.Count; i++)
{
if (filters[i] is CompositeFilterDescriptor compositeFilterDescriptor)
{
compositeFilterDescriptor.FilterDescriptors.NormalizeDateFilters();
}
else if (filters[i] is FilterDescriptor filterDescriptor &&
filterDescriptor.ConvertedValue is DateTime &&
filterDescriptor.Operator == FilterOperator.IsEqualTo)
{
var value = DateTime.Parse(filterDescriptor.Value.ToString());
var start = value.Date;
var end = start.AddDays(1);
var newFilter = new CompositeFilterDescriptor
{
LogicalOperator = FilterCompositionLogicalOperator.And
};
newFilter.FilterDescriptors.Add(new FilterDescriptor
{
Member = filterDescriptor.Member,
MemberType = filterDescriptor.MemberType,
Operator = FilterOperator.IsGreaterThanOrEqualTo,
Value = start
});
newFilter.FilterDescriptors.Add(new FilterDescriptor
{
Member = filterDescriptor.Member,
MemberType = filterDescriptor.MemberType,
Operator = FilterOperator.IsLessThan,
Value = end
});
filters[i] = newFilter;
}
}
return filters;
}

Textbox textmode is DateTimeLocal

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");

C# with Gridview, Access, DateTime and converting

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);

Find highest DateTime from list of DateTime's

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];
}
}

How to convert a date of integers to a formated date string (i.e. 2012009 to 2/01/2009)

Any ideas?
I can't come up with any.
I have a list of dates I'm loading in from a csv file and they are saved as all integers, or rather a string of integers (i.e. Jan 1, 2009 = 1012009)
Any ideas on how to turn 1012009 into 1/01/2009?
Thanks!
Since the date is stored as a string, you may want to use ParseExact:
DateTime date = DateTime.ParseExact("28012009", "dMMyyyy", null);
ParseExact will throw an exception if the format doesn't match. It has other overloads, where you can specify more than a single possible format, if that is required. Note that here provider is null, which uses the current culture.
Depending on style you may wish to use TryParseExact.
int date = 1012009;
var month = date / 1000000;
var day = (date / 10000) % 100;
var year = date % 10000;
var formatted = new DateTime(year, month, day).ToString();
This assumes month-day-year; if the numbers are day-month-year, I’m sure you’ll be able to swap the month and day variables to accommodate that.
If you want to customise the date format, you can do so as described in:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
Let 10102009 be dateInt.
string dateString = dateInt.ToString();
int l = dateString.Length;
dateString = dateString.Insert(l-3,"/");
dateString = dateString.Insert(l-6,"/");
You should now have 1/01/2009 in dateString.. You can also try the ParseExact function..

Categories