formatting datetime column in a DataSet - c#

I have a dataset that is populated by reading excel file. The dataset stores the data from the excel.
The date in the dataset in in the format 2\2\2009 12:00:00 AM but i need the data format converted to 2\2\2009 .
I want to change the format of all the data in that particular column.

Here's one way:
foreach (DataRow row in yourDataTable)
{
DateTime dt = DateTime.Parse(row["Date"].ToString());
row["Date"] = dt.ToShortDateString();
}
This is assuming that the "Date" column is just a text field rather than already a DateTime field.

You can customize the output using a pattern if it is a DateTime object to the format you wanted, "2\2\2009".
string output1 = dt.ToString(#"mm\\dd\\yyyy");
string output2 = dt.ToString("mm/dd/yyyy"); //did you mean this?

A DateTime value or column has no format. It's just binary data.
Where do you want the formatted output to appear? That's where you should apply a format string. For instance, if you wanted it to appear in a column of an ASP.NET DataGrid, then you would set the DataFormatString property of the BoundColumn to "mm/dd/yyyy".

Try this. It will work
var result = from a in ds.Tables[0].AsEnumerable()
select new[] { Convert.ToDateTime(a[0]).ToString("dd/MM/yyyy") };

Related

DateOnly SQL Server type gets converted to TimeStamp in DataSet then in GridView unexpectedly [duplicate]

I have a GridView and I want to export it to Word. I want to change the format of one column to datetime format ("dd.MM.yyyy")
var grid = new GridView { DataSource = dt};
grid.DataBind();
In *.aspx page this is very easy, it looks like in the example below:
<asp:boundfield datafield="My_Date_Column"
dataformatstring="{0:dd.MM.yyyy}"
htmlencode="false" />
I want change format from c#, how to do this?
If you want to alter the format of a column of a GridView from CodeBehind
Add a RowDataBound to your grid view.
Then in the GridView_RowDataBound(object sender, GridViewRowEventArgs e) method, you'll be able to access e which will provide you with access to the individual cells of that row where you can specify a formatter.
Here's an example of using the RowDataBound event
http://forums.asp.net/p/1589807/4025153.aspx
String.Format("{0:dd.MM.yyyy}", myDateTimeInstance);
I think the format of column is based in system current date time format.
But when converting to string you can do so
String str = dt[RowNumber][ColumnName].ToString("dd.MM.yyyy");
DateTime dt = DateTime.Now;
String formated = dt.ToString("dd.MM.yyyy");
OR
String formated = String.Format("{0:dd.MM.yyyy}", dt );
DateTime dt = DateTime.Now;
string formated = dt.ToString("dd.MM.yyyy");
Possible formats are shown in this MSDN article.
In case you want to format the entire column then it would be better if you can set the property for your concerned column
gridview1.Columns[columnIndex].DataFormatString ="{0:dd.MM.yyyy}";
I think you will need to cast the column as BoundField to access the property.

How can I store a formatted DateTime into column of type DateTime in Database?

I'm retrieving data from the database in a dataset and printing it in a pdfdocument. One table has got a DateTime column and the value comes as "12/27/2018 12:00:00 AM". I'm trying to format that as dd/MM/yyyy but with no success since it is expecting a DateTime and formatting return a string value. Should I change the column datatype or there is a way to maintain it and format the datetime?
I recommend changing the database from string to DateTime. But if you cannot you can use something like this
DataTable dt1 = new DataTable();
DataTable dt2 = dt1.Clone();
//change columns type
dt2.Columns["Col A"].DataType = typeof(DateTime);
int colNumber = dt2.Columns.IndexOf("Col A");
foreach (DataRow row in dt1.AsEnumerable())
{
object[] rowData = row.ItemArray;
rowData[colNumber] = DateTime.Parse(row.Field<string>("Col A"));
dt2.Rows.Add(rowData);
}

how can I format this string to MM/dd/yyyy

I have tried a lot of syntax but I can't get it work,
from my DataTable i have this values , please see below
the above values are from the jQuery datepicker, I just make them values in my query.
C#:
I catch the values from the datepicker using this parameter`
List<DateTime> WeekDates
how can i make it to display as 1/6/2016 . thank you for any help!
foreach (DataRow row in dt.Rows)
{
Sale sales = new Sales();
sale.WeekStart = row["WeekStart"].ToString("MM/dd/yyyy");
}
UPDATE
is my date values are string or a DateTime already? I catch the values in my webmethod using this
List<DateTime> WeekDates, but when it comes to my dataTable it has a single quotes , notice it.
Try
foreach (DataRow row in dt.Rows)
{
Sale sales = new Sales();
var date = Convert.ToDateTime(row["WeekStart"]);
sale.WeekStart = date.ToString("MM/dd/yyyy"); // If sale.WeekStart field is string
}
Complete description: http://www.csharp-examples.net/string-format-datetime/
[YourDateTimeVarialble].ToString("MM/dd/yyyy");
[date].ToString("MM/dd/yyyy");
you can use this one
Have you tried
sale.WeekStart =DateTime.Parse(row["WeekStart"].ToString()).ToString("MM/dd/yyyy");
I think this is work for you
Try
(DateTime.ParseExact(row["WeekStart"]), "M/d/YYYY hh:mm:SS tt", System.Globalization.CultureInfo.InvariantCulture)).ToString("MM/dd/yyyy");
If those values came from a database, you may want to format them first before populating to your DataTable. For your desired format, you may refer to this post.
Update 1
Try formatting your jQuery DatePicker to something like:
$(".selector").datepicker({ dateFormat: "MM/dd/yyyy" });
Update 2
foreach (DataRow row in dt.Rows)
{
Sale sales = new Sales();
sale.WeekStart = Convert.ToDateTime(row["WeekStart"]).ToString("MM/dd/yyyy");
}
Try something like this
string date = "1/6/2016 12:00:00 AM";
string d = Convert.ToDateTime(date).ToShortDateString();
O/P : 1/6/2016
In your case perhaps following code will be useful
DataTable dt = new DataTable();
dt.Columns.Add("Date");
DataRow row1 = dt.NewRow();
row1["Date"] = "1/6/2016 12:00:00 AM";
dt.Rows.Add(row1);
DataRow row2 = dt.NewRow();
row2["Date"] = "2/6/2016 12:00:00 AM";
dt.Rows.Add(row2);
List<string> WeekStart = new List<string>();
foreach (DataRow row in dt.Rows)
{
WeekStart.Add(Convert.ToDateTime(row["Date"]).ToShortDateString());
}
try this
string text = row["Weekstart"].ToString();
DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy", null);
Thank you for all who answered my question. As for now the quick solution for me is to remove unnecessary string to display the format MM/dd/yyyy
using this syntax
row["WeekStart"].ToString().Remove(9);
Most of you answered the correct syntax to convert it to the MM/dd/yyyy but I figured out that the values of dates from my jQuery datepicker has a single quote value, what I did is removed it before feeding to my SQL parameters and everything works fine. I already used that syntax before I post here , I just need to remove the single quote in my datetime values.

How to change the format of a column in GridView from c#

I have a GridView and I want to export it to Word. I want to change the format of one column to datetime format ("dd.MM.yyyy")
var grid = new GridView { DataSource = dt};
grid.DataBind();
In *.aspx page this is very easy, it looks like in the example below:
<asp:boundfield datafield="My_Date_Column"
dataformatstring="{0:dd.MM.yyyy}"
htmlencode="false" />
I want change format from c#, how to do this?
If you want to alter the format of a column of a GridView from CodeBehind
Add a RowDataBound to your grid view.
Then in the GridView_RowDataBound(object sender, GridViewRowEventArgs e) method, you'll be able to access e which will provide you with access to the individual cells of that row where you can specify a formatter.
Here's an example of using the RowDataBound event
http://forums.asp.net/p/1589807/4025153.aspx
String.Format("{0:dd.MM.yyyy}", myDateTimeInstance);
I think the format of column is based in system current date time format.
But when converting to string you can do so
String str = dt[RowNumber][ColumnName].ToString("dd.MM.yyyy");
DateTime dt = DateTime.Now;
String formated = dt.ToString("dd.MM.yyyy");
OR
String formated = String.Format("{0:dd.MM.yyyy}", dt );
DateTime dt = DateTime.Now;
string formated = dt.ToString("dd.MM.yyyy");
Possible formats are shown in this MSDN article.
In case you want to format the entire column then it would be better if you can set the property for your concerned column
gridview1.Columns[columnIndex].DataFormatString ="{0:dd.MM.yyyy}";
I think you will need to cast the column as BoundField to access the property.

datetime conversion with specific format

i want to filter the data from a datatable using dataview row filter Datatable having the column name month having like this "01-04-2012 00:00:00". I want to get the get the data using this format..
This is my partial code
dv1 = dtable.DefaultView;
DateTime start = new DateTime(DateTime.Now.Year, 4, 1,0,0,0);
dv1.RowFilter =Convert.ToString(start); //"Month = '04-01-2011 00:00:00'";
it returns the following error : Syntax error: Missing operand after '00' operator. I can't able to fix this error please help me to do this ...
You need to enclose the datetime value into #. You also have to say what column you want to compare with this value.
For example:
dv1.RowFilter = String.Format(CultureInfo.InvariantCulture.DateTimeFormat,
"Date = #{0}#", start);
(where Date is the actual name of your datetime-column)
DataView.RowFilter Property
Using the InvariantCulture Property
Looking at the code, you are missing the name of the column you would want to filter on.
For example:
dv1.RowFilter = string.Format("PurchaseDate = '{0}'", Convert.ToString(start));
The assumption is that PurchaseDate is the date inside the view, the data is to be filtered using.

Categories