DateTime format in SQL - c#

I am having some problem when trying to format DateTime in Asp.net. I wanted the date to display as 18/1//2014 instead of 18/1/2014 12.00 AM. Here is the code:
DataTable dt = new DataTable();
dt.Columns.Add("totalQuantity");
dt.Columns.Add("deliveryDate");
for (int count = 0; count < catSumList.Count; count++)
{
DataRow dr = dt.NewRow();
dr["totalQuantity"] = catSumList[count].productQuantity;
dr["deliveryDate"] = catSumList[count].deliveryDate;
dt.Rows.Add(dr);
}
string[] deliveryDate = new string[dt.Rows.Count];
decimal[] totalQuantity = new decimal[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
totalQuantity[i] = Convert.ToInt32(dt.Rows[i][0]);
deliveryDate[i] = dt.Rows[i][1].ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
}
lcCategory.Series.Add(new AjaxControlToolkit.LineChartSeries { Data = totalQuantity });
lcCategory.CategoriesAxis = string.Join(",", deliveryDate);
lcCategory.ChartTitle = string.Format(categoryName);
lcCategory.Visible = true;
However, it gives me an error message at this line:
deliveryDate[i] = dt.Rows[i][1].ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
The error message is No overload method ToString takes 2 arguments. I wonder is there any other way to format it? My data type for deliveryDate in database is DateTime. Thanks in advance.

Since you are working with DataTables which are weakly typed and not recommended to be used you will need to first cast to a DateTime before being able to apply any format:
deliveryDate[i] = ((DateTime)dt.Rows[i][1]).ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
The Rows property returns an object which you need to cast.

Use:
deliveryDate[i] = ((DateTime)dt.Rows[i[1]).
ToString("dd/M/yyyy",CultureInfo.InvariantCulture);

Related

Adding List of last 18 Months to Drop Down in C#

I have to add last 18 months to a drop down in asp.net C#.
I have written the logic to get last 18 months as follows.,
List<string> dateList= new List<string>();
private List<string> GetDateDropDownList(DropDown pDropDown)
{
DateTime dt = DateTime.Now;
for (int i = 1; i <= 18; i++)
{
dt = dt.AddMonths(-1);
var month = dt.ToString("MMMM");
var year = dt.Year;
dateList.Add(String.Format("{0}-{1}", month, year));
}
return dateList;
}
now I need to add this list to drop down. I am trying but it is not working. How can I add it to the drop down?
Similar to what others have said, you just bind your function to it.
However, you have a little issue in your code. You create your dateList outside of your actual method, instead of inside of it. You also do not need to pass a dropdown list into the method.
So your updated method should be:
private List<string> GetDateDropDownList()// get rid of parameter
{
List<string> dateList= new List<string>(); // inside method
DateTime dt = DateTime.Now;
for (int i = 1; i <= 18; i++)
{
dt = dt.AddMonths(-1);
var month = dt.ToString("MMMM");
var year = dt.Year;
dateList.Add(String.Format("{0}-{1}", month, year));
}
return dateList;
}
And you bind your dropdown direct to the method
myDropdown.DataSource = GetDateDropDownList();
myDropdown.DataBind();
Alternatively, with your original method you can do the following - notice it's now a void and does not return a list.
private void GetDateDropDownList(DropDown pDropDown)
{
List<string> dateList= new List<string>();
DateTime dt = DateTime.Now;
for (int i = 1; i <= 18; i++)
{
dt = dt.AddMonths(-1);
var month = dt.ToString("MMMM");
var year = dt.Year;
dateList.Add(String.Format("{0}-{1}", month, year));
}
pDropDown.DataSource = dateList;
pDropDown.DataBind()
}
And you would simply pass in your dropdown list
GetDateDropDownList(myDropdownList);
All you're doing in your method is building a list. You never add it to the drop down. Like this...
pDropDown.DataSource = dateList;
pDropDown.DataBind();
You are currently building a list of strings, but in order to make it visible within your dropdown, you'll need to specifically set the DataSource property and then call DataBind() to apply the changes:
// This sets your data
pDropDown.DataSource = dateList;
// This actually binds the current data to the DropDownList control
pDropDown.DataBind();
Additionally, you likely won't need to be returning any values from this method (unless you need them for some other reason) and could consider making it return void:
private void SetDatesForDropDown(DropDown pDropDown, int monthsBack = 18)
{
List<string> dateList= new List<string>();
DateTime dt = DateTime.Now;
for (int i = 1; i <= monthsBack; i++)
{
dt = dt.AddMonths(-1);
dateList.Add(dt.ToString("MMMM-yyyy"));
}
pDropDown.DataSource = dateList;
pDropDown.DataBind();
}
Or simply removing the DropDown parameter and using the results of the method to set your DataSource:
private void GetDateRanges(int monthsBack = 18)
{
List<string> dateList= new List<string>();
DateTime dt = DateTime.Now;
for (int i = 1; i <= monthsBack; i++)
{
dt = dt.AddMonths(-1);
dateList.Add(dt.ToString("MMMM-yyyy"));
}
return dateList;
}
along with:
YourDropDown.DataSource = GetDateRanges();
YourDropDown.DataBind();
There are a number of ways of doing this, below is one such way.
Just remember to bind it to a dropdownlist.
EDITED - Getting the Selected Value
Frontend - ASPX
<asp:DropDownList ID="DropDownList1" runat="server" OnLoad="DropDownList1_Load" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
Codebehind - C#
//Populate the DropDownList
protected void DropDownList1_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Instantiate your DropDownList
DropDownList drpList = (DropDownList)sender;
List<string> dateList = new List<string>();
DateTime dt = DateTime.Now;
for (int i = 1; i <= 18; i++)
{
dt = dt.AddMonths(-1);
var month = dt.ToString("MMMM");
var year = dt.Year;
dateList.Add(String.Format("{0}-{1}", month, year));
}
// Bind resulting list to the DropDownList
drpList.DataSource = dateList;
drpList.DataBind();
}
}
//Get the Selected Value on change
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// assign the selected item value to a variable
string value = ((DropDownList)sender).SelectedValue;
}

Dataview rowfilter invalid datetime string

I'm struggling with the following. I have a DataTable with dates in it. Dates that can contain several time rows. Now I want to click on a date on the calender and it will put the times records from that day in a listbox so I can then select the time.
I'm stuck and googled around but I'm blind at this point.
The datatable output in gridview:
Datum
-----------------
22-09-14 13:05:00
22-09-14 13:05:18
23-09-14 13:05:36
23-09-14 13:05:54
23-09-14 13:06:12
21-09-14 14:00:01
21-09-14 15:00:01
21-09-14 16:00:01
21-09-14 17:00:01
The code in the calander SelectionChanged event:
// Create datatable
DataTable dt = new DataTable();
string FileName = "C:\\ProjectName\\data\\data.dat";
var lines = File.ReadAllLines(FileName);
// Make date column
dt.Columns.Add("Datum", typeof(DateTime));
// add rows
for (int i = 2; i < lines.Count(); i++)
{
DataRow dr = dt.NewRow();
string[] values = lines[i].Split(new char[] { ',' }).Select(x => x.Replace("\"", "")).ToArray();
for (int j = 0; j < values.Count() && j < 1; j++)
dr[j] = values[j];
dt.Rows.Add(dr);
}
// Convert selected date
string currentDate = e.SelectedDates.Count - 1 >= 0 ? e.SelectedDates[e.SelectedDates.Count - 1].Date.ToString("dd-MM-yyyy") : "none";
// Print selected date to see format
Label1.Text = currentDate;
// Create dataview and apply filter
DataView dv = new DataView(dt);
dv.RowFilter = "Datum = #" + currentDate + "#";
dv.RowStateFilter = DataViewRowState.ModifiedCurrent;
dv.Sort = "Datum DESC";
// dataview to listbox
lbSource.DataSource = dv;
lbSource.DataTextFormatString = "{0:dd-MM-yyyy HH:mm}";
lbSource.DataTextField = "Datum";
lbSource.DataValueField = "Datum";
lbSource.DataBind();
The dv filter gives me:
String was not recognized as a valid DateTime.
Debugging stops with the following line and gives the "String was not recognized as a valid DateTime.":
dv.RowFilter = "Datum = #" + currentDate + "#";
currentdate comes with the correct date: 22-09-2014 (dd-MM-yyyy)
If someone could help me out, thanks a lot :)
Basically the .rowfilter compare takes the date as Mm/dd/yyyy as comparison. It will see 20/10/2018 as an invalid date. It will work for day being lower than 12.
So in your datatable, the date is stored as dd/mm/yyyy.
Unless you change the date storage format to mm/dd/yyyy, I don't think you can rowsfilter.

Copy date format cell to datatable excellibrary

I'm developing a program in C#, is a desktop application.
I have a problem, I'm using excellibrary to open an excel and copy the data to a datatable, but I have a cell with date in format mm/dd/yyyy, but when i display the datatable in datagridview this information change to a number, for example:
02/07/1984 -> 30865
this is my code, I hope somebody could help me!
private DataTable ConvertToDataTable(string FilePath)
{
string file = FilePath;
// open xls file
Workbook book = Workbook.Open(file);
Worksheet sheet = book.Worksheets[0];
DataTable dt = new DataTable();
// traverse rows by Index
for (int rowIndex = sheet.Cells.FirstRowIndex; rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
{
Row row = sheet.Cells.GetRow(rowIndex);
object[] temparray = new object[row.LastColIndex + 1];
for (int colIndex = row.FirstColIndex;
colIndex <= row.LastColIndex; colIndex++)
{
Cell cell = row.GetCell(colIndex);
temparray[colIndex] = cell.Value;
}
if (rowIndex == 0)
{
foreach (object obj in temparray)
{
dt.Columns.Add(obj.ToString());
}
}
else
{
dt.Rows.Add(temparray);
}
}
return dt;
}
The number you see is OLE Automation Date, you need to convert that number to DateTime by using DateTime.FromOADate Method :
DateTime dt = DateTime.FromOADate(30865); //dt = {02/07/1984 12:00:00 AM}
To use that method in your current code, you have to go through each column's value and for date index, parse the value to DateTime and then add it to the DataTable

insert date of birth into sql server

I made a JavaScript for date of birth, when debugging you choose your day of birth in three drop down boxes. One for days one for months and one for years. I'm working on C# asp.net. The problem is when i click on test(which is submit or confirm) the date is not taken to the database table. It fills empty! Any help would be appreciated..
here's the code:
DateOfBirth.js:
function date_populate(dayfield, monthfield, yearfield)
{
var today = new Date();
var dayfield = document.getElementById(dayfield);
var monthfield = document.getElementById(monthfield);
var yearfield = document.getElementById(yearfield);
for (var i = 0; i < 32; i++)
{
dayfield.options[i] = new Option(i , i + 1)
dayfield.options[today.getDate()] = new Option(today.getDate(), today.getDate(), true, true)
}
for (var m = 0; m < 12; m++)
{
monthfield.options[m] = new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()] = new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true)
}
var thisyear = today.getFullYear()
for (var y = 0; y < 100; y++)
{
yearfield.options[y] = new Option(thisyear, thisyear)
thisyear -= 1
}
yearfield.options[0] = new Option(today.getFullYear(), today.getFullYear(), true, true)
}
Form.asp.cs
protected void Button1_Click(object sender, EventArgs e)
{
String D, M, Y, Full;
D = Day.Value.ToString();
M = Month.Value.ToString();
Y = Year.Value.ToString();
Full = D + "/" + M + "/" + Y;
}
Don't construct dates as strings. Pass them as dates. For example:
DateTime dob = new DateTime(Year.Value, Month.Value, Day.Value);
...
cmd.Parameters.AddWithValue("dob", dob);
where the cmd.CommandText involves #dob when you want to refer to the date of birth.
Format the date 'yyyy-mm-dd' and it will insert.
Are you using a stored procedure?
Change your SP parameter from SqlDbType.NVarChar to SqlDbType.DateTime and then pass the date as a DateTime object to the parameter. You dont need to worry about conversions anymore.
DateTime dateofbirth = new DateTime(Convert.ToInt32(yearfield.SelectedValue),Convert.ToInt32(monthfield.SelectedValue), Convert.ToInt32(dayfield.SelectedValue));
param[0] = new SqlParameter("#DateOfBirth", SqlDbType.DateTime);
param[0].Value = dateofbirth;

How to search people by birthday?

I've found this way, is there any other simplier?
ClienteAdapter cliente = Cache.CacheManager.Get<ClienteAdapter>();
DataTable dt = cliente.GetDataTable();
DateTime dta = DateTime.Today;
String dia = dta.Day.ToString();
if (dta.Day < 10)
dia = '0'+dia;
String mes = dta.Month.ToString();
if (dta.Month < 10)
mes = '0'+mes;
String aniversario = String.Format("{0}-{1}", dia, mes);
dt = cliente.Get(dt, String.Format("WHERE dtNascCli LIKE '%{0}%'", aniversario));
if (dt.Rows.Count>0) {
String aniversariantes = "Aniversariantes do dia:\n";
for (int i = 0; i < dt.Rows.Count; i++)
{
aniversariantes += ((dt.Rows[i]["nmComprador"] != null) : dt.Rows[i]["nmComprador"] ? dt.Rows[i]["nmRazao"]) + "\n";
}
LINQ could get you started.
from DataRow dr in dt.Rows
where ((Date)dr["birthday"]).Month = Date.Today.Month && ((Date)dr["birthday"]).Day = Date.Today.Day
select dr;
That yields an IEnumerable<DataRow>, which you could iterate over with a foreach.
EDIT: Incorporated bemused's comment regarding previous years.
You could simplify this:
DateTime dta = DateTime.Today;
String dia = dta.Day.ToString();
if (dta.Day < 10)
dia = '0'+dia;
String mes = dta.Month.ToString();
if (dta.Month < 10)
mes = '0'+mes;
String aniversario = String.Format("{0}-{1}", dia, mes);
Into this:
String aniversario = DateTime.UtcNow.ToString("dd'-'MM");
// You *are* storing dates in UTC aren't you?
This doesn't change the fact that this isn't a good way to store or search for dates, but its a good place to start.
That's all I got, besides Jim Dagg's LINQ example.

Categories