Convert datetime format using linq - c#

I am using ASP.NET3.5 with C# 2008 and I am novice to use LINQ. I have a dataset to which I am fetching table's data that includes a column with type datetime. Now, I want to convert this date in 24 hours format with Date and Hours, Minutes and seconds only. The stored date time is in 12 hours format. I have tried
ds.Tables[0].AsEnumerable().ToList().ForEach(i => i["CreatedDate"] = Convert.ToDateTime(i["CreatedDate"].ToString()).ToString("MM/dd/yyyy HH:mm:ss"));
and then I am passing the dataset to gridview as a datasource.
It is not giving any exception but it is not converting the date into 24 hours format.
Can anyone help please.
Awating for your valuable response..
Thank you,
Dev

"The stored date time is in 12 hours format" No, the string which represents a DateTime is formatted, a DateTime never has a format. Use a DateTime when you store a DateTime, use a string only when you want to display it. If it's already a DateTime in your DataSet you don't need to convert it to a string and back to a DateTime via Convert.ToDateTime(i["CreatedDate"].ToString()).
This code is a mess, sorry:
ds.Tables[0].AsEnumerable().ToList().ForEach(i => i["CreatedDate"] = Convert.ToDateTime(i["CreatedDate"].ToString()).ToString("MM/dd/yyyy HH:mm:ss"));
Why?
You are converting a DataTable to a List<DataRow> although a DataTable is already a in-memory object. That is pointless and inefficient
You are storing a DateTime as string, you can use DateTime as type for a DataColumn in a DataTable, convert it to a string at the very last stage when you want to display the value
You are converting the "string-date" to a datetime, using ToString to format it as string and then you're converting it again to a datetime. This will use the default ToString(with your curentculture) to diplay it which is the reason why you don't get the desired format
So assuming that is's really a string and you don't want/can change it to DataTime, this might work:
var query = ds.Tables[0].AsEnumerable()
.Select(r => Date.Parse(r.Field<String>("CreatedDate")).ToString("MM/dd/yyyy HH:mm:ss"));
gridView1.DataSource = query;
gridView1.DataBind();
Note that you could also use the DataFormatString property of the GridView's BoundField:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="CreatedDate"
HeaderText="Created-Date"
SortExpression="CreatedDate"
DataFormatString="MM/dd/yyyy HH:mm:ss" />
But then you need to store it as/convert it to a DateTime in the table and use that as DataSource.

I hope It will work. You can try this one.
ds.Tables[0].AsEnumerable().ToList().ForEach(i => i["CreatedDate"] = Convert.ToDateTime(i["CreatedDate"].ToString()).ToString("HH:mm:ss"));

Related

Datetime Format Convert C#

Here is my date time format displayed
Dr["DATE"] =========> Jun 27 2014 9:06PM
I want it to display like this one =========> 27.06.2014
Here is my code:
ltrlNotlar.Text = Dr["DATE"].ToString()
How to change first format to the second one?
Thankss
use DateTime to do the conversion for you
var dt = DateTime.Parse(Dr["DATE"].ToString());
ltrlNotlar.Text = dt.ToString("dd.MM.yyyy");
If Dr is a DataRow, you can this
ltrlNotlar.Text = dr.Field<DateTime>("DATE").ToString("dd.MM.yyyy");
I like using .Field because it does the casting for you. However this only works if the sql column is a Date or DateTime (or possibly DateTimeOffset). If you are storing your date as a string in the database, this won't work.
If the sql column DATE is nullable, make sure to change the generic argument to DateTime?.
you could also use something like this:
Convert.ToDateTime(SomeDateTime).ToString("MM.dd.yyyy");

OleDb return Date Column value with time

I have Excel File(.xls) which contain date column without time value. I am trying to read this file and put it in datatable with connection string as below:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Test\Desktop\1.xls; Extended Properties="Excel 8.0;HDR=YES;IMEX=1;ImportMixedTypes=Text"
Excel File Data
OleDb return datem value with time. 7/20/1995 12:00:00 AM
DataTable Data
But i want datem column value without time. Anyone have idea what i have to do to solve my problem.
Thanks.
.Net framework's DateTime consist of Date and Time. You can't really separate Time part from DateTime, instead you can use custom format for displaying records.
string str = DateTime.Today.ToString("MM/dd/yyyy");
I assume it's just a display issue in the DataSet visualizer. Actually it's a DateTime column which has no inherent format. So if you want to output a DateTime only with the date part:
string date = dt.ToShortDateString(); // or dt.ToString("d")
The Short Date ("d") Format Specifier

GETDATE() always returns 12:00:00 AM

In my ASP.NET (C#) project, I'm inserting some data into a database.
INSERT INTO USERS (username,join_date) VALUES('Ali',GETDATE());
Now when I'm fetching the date from the database, I'm using DateTime.
SqlDataReader r = Command.ExecuteReader();
r.Read();
myDate = r.getDateTime(0);
And when I'm inserting this in some DIV, I do this.
"<div>"+myDate.ToLongTimeString()+"</div>"
I get the correct date as in day/month/year, but the hour is always 12:00:00 AM.
How can I get the exact time?
make sure join_date is of type DATETIME and not DATE in the database
http://msdn.microsoft.com/en-us/library/ms186724.aspx
Using DATE as your column type means you are only storing the date not the time.
Therefore when you read the value back into a DateTime object the system has to initialise the time part - to midnight.
Convert the column to DATETIME and you'll get the time component stored as well.
For more information on the difference see the MSDN page on Date and Time Data Types and Functions

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

Converting MySQL DATETIME to System.DateTime

I am using a MySQL database with DbLinq, but there is an exception being thrown:
"Cannot convert mysql datetime to
system.datetime"
How can I resolve this issue?
Check for any zero date means date like '0000-00-00' in database;
this could be the cause of error.
Either cast the MySqlDateTime as a DateTime or use mySqlDateTime.GetDateTime().
Well, if you have a result set containing MySql DateTime values, you could use the ConvertAll method along with a delegate using DateTime.Parse to create a collection of System.DateTime values.
Here's an example, where "results" is the result of your dblinq query containing MySQL datetime values:
List<DateTime> dateTimes = results.ConvertAll(delegate(string time){
return DateTime.Parse(time);
});
Is this what you're looking for?
I was moving a column in my gridview from asp:BoundField to asp:TemplateField so had to display a date from a MySQL database explicitly. I found, through reflection, that the collection typed the date fields as MySqlDateTime and not system.DateTime.
I added the import MySql.Data.Types statement to the code behind and the following Eval statement within a label in the context of a gridview.
Text='<%# CType(Eval("Submitted_Date"), MySql.Data.Types.MySqlDateTime).ToString%>'
output format: 02/23/2011
Hope that helps!

Categories

Resources