Consider i have a datatable dt and it has a column DateofOrder,
DateofOrder
07/01/2010
07/05/2010
07/06/2010
I want to format these dates in DateOfOrder column to this
DateofOrder
01/Jul/2010
05/Jul/2010
06/Jul/2010
Any suggestion..
The smartest thing to do would be to make sure your DataTable is typed, and this column is of type DateTime. Then when you go to actually print the values to the screen, you can set the format at that point without mucking with the underlying data.
If that's not feasible, here's an extension method I use often:
public static void Convert<T>(this DataColumn column, Func<object, T> conversion)
{
foreach(DataRow row in column.Table.Rows)
{
row[column] = conversion(row[column]);
}
}
You could use in your situation like:
myTable.Columns["DateOfOrder"].Convert(
val => DateTime.Parse(val.ToString()).ToString("dd/MMM/yyyy"));
It only works on untyped DataTables (e.g. the column type needs to be object, or possibly string).
.ToString("dd/MMM/yyyy")
(assuming your data is DateTime type)
Just expounding on saille's answer here:
For a DateTime, format isn't an issue. A DateTime is actually the number of ticks counting up from midnight, January 1, 1 A.D. So, really, it's just a long. Formatting only becomes an issue when it comes time to convert it into a string. So, you'll have to go and take care of the formatting either when you pull it out of the data table and are ready to output it, or put it into the data table as a string (which I would not recommend, for flexibility purposes). The formatting can be done with the .ToString call on the DateTime that saille suggests, .ToString("dd/MMM/yyyy")
Just to add, you need to put your extension method to a .cs file usually some sort of a Utility.cs and then get access to that with the help of using statement.
A complete example is provided here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
Related
I have a C# program that reads data from a CSV file into a DataTable. This means that all the columns in the resultant DataTable are strings. I then need to Select from the DataTable a subset of rows that match the criteria of a shared value within a single column. This works fine.
My problem comes in that I also need the return set sorted by another column which is a date. I cannot figure out how to format that sort parameter in the Select function to convert the string expression of the date to a real date so the sort works properly.
Can this be done with the Select statement or do I need to take another approach?
You can load file using schema.ini https://msdn.microsoft.com/en-us/library/ms709353.aspx and define type for your columns
Here is one thing you can try. This will iterate over each row in the DataTable and get the String of the date from the column that you specify. It will turn the String into a DateTime using TryParse. If this succeeds, Row[0] will be set to the DateTime. If it fails, row[0] will not be changed.
I have set the column to 0 in the below code, but you should change all 0's to whatever column the DateTime is in.
DateTime dateValue;
foreach(DataRow row in dtDataTable.Rows){
if(DateTime.TryParse(row[0], out dateValue)){
row[0] = dateValue
}
}
You can find more info on TryParse here. TryParse can have unpredictable behavior, so for even more control I would recommend upgrading to TryParseExact once you get this working.
I know the question is a bit confusing. Please let me elaborate.
Suppose
I have a table student master which has a column DOB
I have inserted a record and in DOB I have inserted '1991-01-01'
running select statement from sql server is returning date in the same format as it is inserted '1991-01-01' but when I am running the same query from C# using SqlDataAdapter then its returning date as '01-01-1991'
Can anyone explain why it is happening and is there any way to fetch the date in same format as it is inserted.
Query
Is it possible to get the DateTime using SqlDataAdapter as it was inserted?
P.S: column data type is Datetime
let's separate the wheat from the chaff :)
if for your needs meaningful is data type (datetime in this case), then formatting does not matter at all. All layers which will exchange or process the data will use data type information for that.
But
if the meaningful part is formatting, i.e. string representation of the data, then you need to consider the appropriate settings of UI tools you use to display your data. SSMS, for example, uses regional settings for that. If you need to visualize data in the identical manner, so you need the identical strings, you should take care of formatting by your self or in another words, you need to convert your datetime data to string in the same way in all places where you need it.
In T-SQL, for example, you could use CAST and CONVERT functions for formatting your data in a format you need.
If you can't match up the "Cultures" between the SQL Server and the machine you're building the application on (and, in fact, you cannot rely on that really if you're application is going to be deployed to other machines!), then the cheap and quick way round it is to run your date returns through a parse function such as this:
private string FncFormatDate(string date)
{
DateTime formattedDate;
if (DateTime.TryParse(date, out formattedDate))
{
return formattedDate.ToString("yyyy-MM-dd");
}
else
{
return "Invalid date";
}
}
I hope this answers your question.
I have a grid that is populated using an Oracle 11g query that returns a TIMESTAMP(6) WITH TIME ZONE field along with other fields.
When I select a date range for data to be displayed that goes from 12/26/2014 to 1/5/2015, and then try to sort by this column (asc or desc), it does not sort properly. For example, in desc order it displays from 01/01 to 01/05 and then from 12/26 to 12/31. Looks like string sorting.
I am guessing a TIMESTAMP(6) WITH TIME ZONE field that contains a value like 21-JAN-2015 18:17:16:00000 USA/EASTERN is not recognized as a date-time but rather a string. Is there any way to resolve this issue?
Turning a comment into an answer:
There is a number of options:
(i) Rely on the database to sort the data correctly - which you might want to prevent for performance reasons.
(ii) Instruct the grid to handle the timestamp column as such (and not as a string column) - which might not be possible.
(iia) Use a different grid component, which handles date columns properly.
(iii) Use a hidden (string) column with the timestamp formatted as 'YYYY-MM-DD HH24…' for sorting.
(iv) Write your own sort routine.
Feel free to provide more detail if and as you see fit.
I have a Dataset with a Bunch of Columns used in a Report (DevExpress XtraReports) (DataSet being the DataSource). The Dataset has many columns, and i need to read a column (based on the row type), and decide which column value to read for the row, and apply formatting based on the row type.
Example:
DataSet
DataType IntValue RealValue StringValue DateValue
Int32 123
DateTime 1/1/2011 1:23 AM
String XYZ
...
If the Datatype is DateTime, i need to read the DateValue column value, etc
I know we can use DataSet Expressions on computed columns, but cant find a way to apply the required Expression, and Format Data for the Report.
Is there a suggested way to handle this in the Report or at DataSet Level (excepting the formatting part)?
I'm not sure why you are taking this approach. This dataset is filled from a SQL datasource or some sort of backend? if that is the case, why don't you just get the computed column in the right format from the SQL directly? Wouldn't be a performance overhead to loop through all records to try and compute the "right" column?
Since it is a report, wouldn't displaying the data be enough? if you really need to use the type, you can bring that from sql as well, so you end up only with two columsn, type and data. If you can elaborate a little bit more on what you are trying to do, it will be helpful.
I have a column in my table which has a DataType of 'timestamp'. Now I am inserting a row through LINQ2SQL. Now what should I write here:
Entity_Product_Point ev = new Entity_Product_Point();
ev.DateCreated = ???
Thanks!
Are you SURE you wanted timestamp? It has nothing to do with dates... If you'd like to store "DateCreated", I think you probably want to use either a DateTime or just Date datatype in MSSQL. If that's what you really intended, then you can pass in DateTime.Now for a value.
Well the corresponding type would be byte[], but this type is used internally by SQL Server for row versioning—and by ORMs for optimistic locking. You should never (can't) write a value out for a timestamp column manually.
For a more complete listing of which type correspond to what, check out this question