How to search people by birthday? - c#

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.

Related

notification needed for expiry date in datagridview

I badly need advice on this because I'm not familiar with this foreach statement. So, I need to have a notification popup for the expiring items in the inventory. At least 7 days before the items are nearing expiry the system pops up a notification for the user. So, here I tried coming up with the code but it is not yet complete.
foreach (DataGridViewRow row in InventoryList.Rows)
{
foreach (DataGridViewColumn col in InventoryList.Columns)
{
InventoryList.Rows.[4].Cells[col.Index].Value =
}
MessageBox.Show("Nearing Expiry" + "#ItemName");
}
Here is the system, so I need to know which items are nearing expiration for at least 7 days before its expiry
You can try something like this:
var nowPlusOneWeek = DateTime.Now + new TimeSpan(7, 0, 0, 0);
var expiringItems = InventoryList.Rows.Cast<DataGridViewRow>().
Where(x => x.Cells[0].Value != null && Convert.ToDateTime(x.Cells[3].Value.ToString()) <= nowPlusOneWeek);
var Expiry = new StringBuilder();
foreach (var item in expiringItems)
Expiry.Append("Nearing Expiry: " + item.Cells[0].Value.ToString() + "\n");
MessageBox.Show(Expiry.ToString());
Update:
Here are more codes to test it on some random data:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
FillTable();
}
private void FindBT_Click(object sender, EventArgs e)
{
FindExpiring();
}
private void FindExpiring()
{
var nowPlusOneWeek = DateTime.Now + new TimeSpan(7, 0, 0, 0);
var expiringItems = InventoryList.Rows.Cast<DataGridViewRow>().
Where(x => x.Cells[0].Value != null &&
DateTime.ParseExact(x.Cells[3].Value.ToString(), "dd/MM/yyyy",
CultureInfo.InvariantCulture) <= nowPlusOneWeek);
var Expiry = new StringBuilder();
foreach (var item in expiringItems)
Expiry.Append("Nearing Expiry: " + item.Cells[0].Value.ToString() + "\n");
MessageBox.Show(Expiry.ToString());
}
void FillTable()
{
Random RND = new Random();
DataTable dt1 = new DataTable();
dt1.Columns.Add("InventoryID", typeof(int));
dt1.Columns.Add("ItemID", typeof(int));
dt1.Columns.Add("Quantity", typeof(int));
dt1.Columns.Add("ExpityDate", typeof(string));
for (int i = 0; i < 10; i++)
{
DataRow dr1 = dt1.NewRow();
dr1["InventoryID"] = i;
dr1["ItemID"] = 1;
dr1["Quantity"] = 20;
dr1["ExpityDate"] = (DateTime.Now + new TimeSpan(RND.Next(20), 0, 0, 0)).ToString("dd/MM/yyyy");
dt1.Rows.Add(dr1.ItemArray);
}
InventoryList.DataSource = dt1;
}
}
OutPut:
1, Add new column call Expired Status to your datagridview.
2,
foreach(DataGridViewRow item in dgvDenominations.Rows)
{
if (DateTime.Now.AddDays(7).Equals(DateTime.Parse(item.Cells["yourdateexpriedcellname"].Value.ToString())))
{
item.Cells["ExpiredStatus"].Value = "Nearing Expiry";
// orr message if you want
}
}
Hi Jonathan try this example
DataGridView grd = new DataGridView();
grd.Columns.Add("Id", "Id");
grd.Columns.Add("citemName", "Item Name");
grd.Columns.Add("dExipryDate", "Expires On");
grd.Rows.Add("1", "Soap", "21 august 2018");
grd.Rows.Add("2", "Soap2", "21july 2018");
grd.Rows.Add("3", "Soap3", "30 august 2018");
grd.Rows.Add("4", "Soap4", "27 june 2018");
grd.Rows.Add("5", "Soap5", "21 march 2018");
grd.Rows.Add("6", "Soap6", "28 september 2018");
grd.Rows.Add("7", "Soap7", "23 october 2018");
foreach (DataGridViewRow drow in grd.Rows) {
DateTime expdate = DateTime.Parse(drow.Cells["dExipryDate"].Value.ToString());
TimeSpan tmspn = expdate - DateTime.Now.Date;
if (tmspn.Days < 7 && tmspn.Days >0)
{
//tmspn.Days >0 if you want to show already expired item
MessageBox.Show(drow.Cells["dExipryDate"].Value.ToString() + "Will Expire in " + tmspn.Days + "Days");
}
}

C# WinForm error import from excel to database

Hei. I need to understand why I receive an error like that :
C# windows form import from excel error
I can't separe the year from string (year time). Or, can I renounce at split and import directly the string as "date"? Sorry, I'm too beginner in c#, but I need this help, is a task for me.
Here is my code :
for (int i = 0; i < dvColumns.Count; i++)
{
string columnName = string.Empty;
string columnField = string.Empty;
if ((dvColumns[i]["Header"] != null) && (!Convert.IsDBNull(dvColumns[i]["Header"])))
{
columnName = dvColumns[i]["Header"].ToString();
}
if ((dvColumns[i]["Field"] != null) && (!Convert.IsDBNull(dvColumns[i]["Field"])))
{
columnField = dvColumns[i]["Field"].ToString();
}
rangeObject = cellsObject.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, cellsObject, new object[] { row, i + 1 });
object valueObject = rangeObject.GetType().InvokeMember("Value", BindingFlags.GetProperty, null, rangeObject, null);
if (columnName == "FiscalCode" && columnField == "PartnerId")
{
string fiscalCode = Erp.Core.Utils.GetStringFromObject(valueObject);
partnerId = p.GetPartnerIdByFiscalCode(fiscalCode);
eventRow["PartnerId"] = partnerId;
}
else if (columnField == "StartDate" || columnField == "EndDate")
{
string date = Erp.Core.Utils.GetStringFromObject(valueObject);
DateTime columnDate = DateTime.Now;
string[] dateComponents = null;
int year = 0;
int month = 0;
int day = 0;
if (date.Contains("."))
{
dateComponents = date.Split('.');
}
if (date.Contains("/"))
{
dateComponents = date.Split('/');
}
if (date.Contains(":"))
{
dateComponents = date.Split(':');
}
if (dateComponents.Length > 1)
{
string s = dateComponents[0];
day = Erp.Core.Utils.GetIntFromObject(s);
s = dateComponents[1];
month = Erp.Core.Utils.GetIntFromObject(s);
s = dateComponents[2];
year = Erp.Core.Utils.GetIntFromObject(s);
columnDate = new DateTime(year, month, day, 9, 0, 0);
}
eventRow[columnField] = columnDate;
}
else if (columnField != "PartnerId" && columnField != "StartDate" && columnField != "EndDate")
{
eventRow[columnField] = valueObject;
}
}
I tried to keep in excel same format as in database table : 'yyyy/mm/dd hh:mm:ss.000'.
The line date = Erp.Core.Utils.GetStringFromObject(valueObject); get my date from first excel cell.
ds.Tables["Events"] is all time empty.
I know this line eventRow[columnField] = date; must add the dates in DB, really? After split, day is ok (receive an int by s[0]), month is ok (receive an int by s[1], but s[2] for year is something like 2017 19:06:22 .... year plus time). I tried to split again by space, but without results, to keep the number (2017) in year variable.
Best way is to use DateTime.ParseExact method. In your case, if original format is 'yyyy/mm/dd hh:mm:ss.000', you can convert it to DateTime like this:
//string date = Erp.Core.Utils.GetStringFromObject(valueObject);
string date = "2017/08/15 10:20:30.000";
DateTime columnDate = DateTime.ParseExact(date, "yyyy/MM/dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
This way you can skip parsing excel string.
In your example, usage will be like this:
//...snip...
else if (columnField == "StartDate" || columnField == "EndDate")
{
string date = Erp.Core.Utils.GetStringFromObject(valueObject);
//parsing date string
DateTime columnDate = DateTime.ParseExact(date, "yyyy/MM/dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
eventRow[columnField] = columnDate;
}
else if (columnField != "PartnerId" && columnField != "StartDate" && columnField != "EndDate")
{
eventRow[columnField] = valueObject;
}
if hours are in 12-hour format, use lowercase hh, like this "yyyy/MM/dd hh:mm:ss.fff"

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.

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;

DateTime format in SQL

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);

Categories