Sort DataTable based on date column(dd MMM yyyy) - c#

I have a dataset ds and i need to sort the datatabel of the same ds based on a column and the column name is Date. The values on this column is in 'dd MMM yyyy' format.

If you can't change the column type to Date then try Linq solution as below
var recs = dataset.Tables[0].AsEnumerable()
.OrderBy(x =>DateTime.ParseExact(
x.Field<string>("Date"),
"dd MMM yyyy",
CultureInfo.InvariantCulture));

That's going to be a problem particularly if it's a large table. The best answer of course, would be to redefine the column as a date type. That way it'll sort and join efficiently. If the table is not large, though, you can reformat the date string to ISO format (YYYY-MM-DD), and it will sort correctly. You didn't mention which database you using, and the string and date functions vary among platforms: here's a SQL Server example:
SELECT CAST([Date] AS Date) AS real_date,
my_other_fields
FROM MyTable
I'm at home, so I don't have a SQL Server to test this on right now (I can update the example in the morning if it doesn't work), but that date format is pretty unambiguous to parse, so I expect that the cast will work okay.
If you want to take care of this entirely on the application side, it should be fairly straightforward to write a string function will reorder the year, month and day in the date string.

Related

How do you return only the date of a datetime field, and make it sortable?

I looked at this question, but it wasn't really the same:
How to return the date part only from a SQL Server datetime datatype
What I need to do is return just the date piece, but also make it so that it sorts properly.
I currently have this:
convert(varchar(10),a.Work_Start,101) as [Work Start]
I'm using this in a sortable gridview in C#. The problem is, when I sort it in ascending order, 01/07/2016 comes before 12/30/2015 because 01 comes before 12. So, I think converting to varchar isn't what I want.
What if you cast the the DATETIME to DATE.
For example:
SELECT CAST(Work_Start AS DATE) AS [Work Start]

Sorting dates in DataGridView

I'm pulling different info from a SQL table using sqlDataReader.
One of the columns contains DateTime, and is pulled from the sql and displayed correctly, using:
var datestring = reader.GetDateTime(reader.GetOrdinal("deadline")).ToShortDateString();
It is shown in the DataGridView in the following format: dd.MM.yyyy
When I try to sort this, it sorts it after dd, no matter what the MM and yyyy info is.
The datestring is put in the datagridview with the following command:
dgv_tasks.Rows.Add(tid, taskname, sidvariable, datestring);
Anyone knows why it's not sorting this as dates at all, just the number in dd ?
(I've looked here for an answer, but none of the similar questions had a working answer).
You want to leave it as a DateTime in the DataGridView, not convert it to a string. That's why it's sorting alphabetically, instead of by date.
Remove .ToShortDateString() and define your DataGridViewColumn as a DateTime type (assuming you're creating the columns manually).
After assigning the data to the DataGridView, just modify that column's DefaultCellStyle.Format value to display the date in whatever you manner you choose:
dgv_tasks.Columns["deadline"].DefaultCellStyle.Format = "dd.MM.yyyy";
It's sorting alphabetically because you converted it to a string.
Try using the date value in your datagridview with a formatter for displaying purposes.

i want to select data when date between dd/mm/yyyy and dd/mm/yyyy

I want to select data where date between dd/mm/yyyy and dd/mm/yyyy
If the date in the same month I find data
For instance
SELECT *
FROM Table Name
WHERE date between '21/07/2014' and '29/07/2014'
If the date between two different Months .. the result is Null
For instance
SELECT *
FROM Table Name
WHERE date between '21/07/2014' and '1/08/2014'
When using dates in SQL Server it pays to be explicit. In your second example it's likely SQL Server is converting the second date to 8th January 2014 as it will assume US style formatting like mm/dd/yyyy. I always write my date in yyyy-mm-dd format but it's probably better to use ISO8601 format as YYYYMMDD which (as marc_s points out) is a much more universal format:
SELECT *
FROM TableName
WHERE date between '20140721' and '20140801'
Dates don't have formats. Since you cite C#, it seems that this code is coming from a .NET caller - in which case, parameterize:
DateTime from = ..., to = ... // perhaps DateTime.Parse or DateTime.ParseExact,
// but perhaps DateTime.Now.Date.Add(...)
cmd.CommandText = #"
SELECT *
FROM Table Name
WHERE date between #from and #to";
cmd.Parameters.AddWithValue("from", from);
cmd.Parameters.AddWithValue("to", to);
Now there is no ambiguity whatsoever.
Use the ISO 8601 universal format. e.g. '2007-04-05T14:30'. It is interpreted regardless of locale settings.
http://en.wikipedia.org/wiki/ISO_8601#Dates
If you absolutely want to use DD/MM/YY format that is style 103 if you convert, ie.
select *
from tbl
where dt between convert(date,'21/07/2014',103) and convert(date,'01/08/2014',103)
See fiddle at: http://sqlfiddle.com/#!6/f199c/6/0
http://www.w3schools.com/sql/func_convert.asp
You can also write you'r query like this
SELECT *
FROM Table Name
WHERE date between '21-Aug-2014' and '1-Sep-2014'

SQL DateTime alternative to only HH:MM:SS for easy coding in C# Linq

Hi guys I am looking for the proper Datatype. Basically I only need time in HH:MM:SS for an SQL Record. I am confused to choose between string, Int(seconds) or some SQL variation of DATETIME that makes it easy for in terms of Coding to sort, select, display etc using Linq-C#
you can use Time datatype or convert your datetime to 'hh:mm:ss' - convert(nvarchar(8), <your column>, 108)

Propagate a DateTime column of a DataSet to database

I have a DataSet that has a timestamp (i.e. Datetime.Now ) recording the date and time when a row is added to the DataSet in memory. I will later save (or propagate) all these rows to the SQLCE database where the DataSet's timestamp will be propagate to a DateTime column in the database table.
It works fine and datetime comparison is also ok:
dataView1 = new DataView(
dt,
"DataTime >= '6/9/2011 5:00:20 PM'",
"Data_ID ASC",
DataViewRowState.CurrentRows);
The above code works ok, but I worry if the program runs on different computer (i.e. another language of Windows) the Datetime.Now format would have a different format, or if I compare data that is record from a different computer, the different format of the DateTime in the database will causes it to fail. Would this problem happen? Or is there a safer way of doing this?
String datetime = String.Format("{0:G}", ur_datetime_variable);
will give you string in M/d/yyyy h:mm:ss tt format and then convert the datetime string to DateTime
here's a link http://www.csharp-examples.net/string-format-datetime/ and there's everything bout datetime formating.
Should you not use CultureInvariant
DateTimeFormatInfo.InvariantInfo
when parsing dates

Categories

Resources