when reading SQl Date time field , only i can take the date with time ..how to get only date in to text box from Ajax or some method.
this is what i need to do
http://i.stack.imgur.com/n0fgG.jpg
that's how I'm taking the date to text box.
protected void ddlBatch_SelectedIndexChanged(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["CBConnectionString"].ConnectionString;
const String strQuery = "select ItemIdentityCode, Qty, PurchasingPrice, ExpireDate, DiscountRate, IssueMode, Principle, Force from DEL_PurchasesLines where BatchNumber = #BatchNumber";
SqlConnection conPR = new SqlConnection(strConnString);
SqlCommand cmdPR = new SqlCommand();
cmdPR.Parameters.AddWithValue("#BatchNumber", ddlBatch.SelectedItem.Value);
cmdPR.CommandType = CommandType.Text;
cmdPR.CommandText = strQuery;
cmdPR.Connection = conPR;
try
{
conPR.Open();
SqlDataReader sdr = cmdPR.ExecuteReader();
while (sdr.Read())
{
tHFExpiaryDate.Text = sdr["ExpireDate"].ToString();
}
}
catch (Exception ex)
{
//throw ex;
}
finally
{
conPR.Close();
conPR.Dispose();
}
}
Don't convert the raw value to a string in the first place - it should already be a DateTime:
DateTime date = (DateTime) dsr["ExpireDate"];
Then you can convert it into whatever format you're interested in:
// TODO: Consider specifying the culture too, or specify a standard pattern.
tHFExpiaryDate.Text = date.ToString("MM/d/yyyy");
It's important to separate the question of "How can I get the data from the database in an appropriate type?" from "How should I present the data to the user?"
Try something like:
DateTime.ParseExact(sdr["ExpireDate"].ToString(), "MM/d/yyyy", CultureInfo.InvariantCulture)
In your sample:
tHFExpiaryDate.Text = DateTime.ParseExact( ((DateTime)dt.Rows[0][0]).ToString("MM/d/yyyy"), "MM/d/yyyy", System.Globalization.CultureInfo.CurrentCulture).ToString("MM/d/yyyy"));
This always works for me
protected String getDate(string date)
{
DateTime dDate;
string sdate = null;
if (!string.IsNullOrEmpty(date.ToString()))
{
dDate = DateTime.Parse(date.ToString());
sdate = dDate.ToString("dd/MM/yyyy");
sdate = dDate.ToLongDateString();
}
return sdate;
}
Other date format example http://www.dotnetperls.com/datetime-format
Related
I figured out I'm not parsing Date value as I should. But I'm unsure on how to do it.
I know I should manually parse date value, but to be honest I don't know how to do it.
private void BtnDodajDavaoca_Click(object sender, EventArgs e)
{
String query = "INSERT INTO Davaoci (Ime,Prezime,Pol,DatumRodjenja,KrvnaGrupa,Tezina,Adresa,BrojTel,BrojLK) VALUES (#Ime, #Prezime, #Pol, #DatumRodjenja, #KrvnaGrupa, #Tezina, #Adresa, #BrojTel, #BrojLK)";
using (SqlConnection cs = new SqlConnection(#"Data Source=DESKTOP-112OILD\SQLEXPRESS;Initial Catalog=DDK;Integrated Security=True"))
using (SqlCommand InsertDavaoc = new SqlCommand(query, cs))
{
InsertDavaoc.Parameters.Add("#Ime", SqlDbType.NVarChar).Value = TxtIme.Text;
InsertDavaoc.Parameters.Add("#Prezime", SqlDbType.NVarChar).Value = TxtPrezime.Text;
InsertDavaoc.Parameters.Add("#Pol", SqlDbType.NChar).Value = TxtPol.Text;
//IT'S THIS LINE InsertDavaoc.Parameters.Add("#DatumRodjenja", SqlDbType.Date).Value = DtpDatumRodjenja.Text;
InsertDavaoc.Parameters.Add("#KrvnaGrupa", SqlDbType.VarChar).Value = TxtKrvnaGrupa.Text;
InsertDavaoc.Parameters.Add("#Tezina", SqlDbType.Float).Value = TxtTezina.Text;
InsertDavaoc.Parameters.Add("#Adresa", SqlDbType.NVarChar).Value = TxtAdresa.Text;
InsertDavaoc.Parameters.Add("#BrojTel", SqlDbType.NVarChar).Value = TxtBrojTel.Text;
InsertDavaoc.Parameters.Add("#BrojLK", SqlDbType.NVarChar).Value = TxtBrojLK.Text;
cs.Open();
InsertDavaoc.ExecuteNonQuery();
cs.Close();
OsvjeziDgDavaoci();
ClearTxtBx();
}
}
The safe way in converting a string to a date is to use the ParseExact method, that allow you to specify the format in a deterministic way:
// Use custom formats with M and MM.
var dateString = "5/01/2009 09:00";
try {
dateValue = DateTime.ParseExact(dateString, "M/dd/yyyy hh:mm", enUS, DateTimeStyles.None);
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
dateValue.Kind);
}
catch (FormatException) {
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
}
you must use DatePicker instead of TextBox for this reason, but you can use Parse Method for parsing string to DateTime:
DateTime.Parse(TxtDatumRodjenja.Text);
You can also use below code to convert your string date to dot net compatible date object like
InsertDavaoc.Parameters.Add("#DatumRodjenja", SqlDbType.Date).Value = Convert.ToDateTime(DtpDatumRodjenja.Text);
I'm populating a datagridview with data and one of the columns should be shown as time i.e. hh:mm:ss.
The data is extracted from the Access database and successfully populates in the datagridview. The column I want to show as time is populated in the access database as "Number". As you will see I covert it down to seconds using /86400 within the select query.
When I try to convert the column using DefaultCellStyle.Format = "hh:mm:ss tt", the entire column of data is replaced with just "hh:mm:ss tt" in each cell i.e. there are no longer numbers, its just hh:mm:ss tt in every cell.
Below is my code - can anyone advise what I am doing wrong?
string strProvider =
"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = P:\\JC_StockFile\\Mitel\\Mitel.accdb";
string strSql =
"SELECT [MidnightStartDate], [Agent Name], [LoginTime], [LogoutTime], [ShiftDuration]/86400 as ShiftDuration " +
"FROM login_data " +
"WHERE [MidnightStartDate] > #LeDate";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#LeDate", DateTime.Today.AddDays(-3) );
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
dataGridView1.DataSource = scores;
dataGridView1.Columns["ShiftDuration"].DefaultCellStyle.Format = "hh:mm:ss tt";
I believe this property works like other String Formats. Edit: I think actually you just have an upper case issue:
Try this:
dataGridView1.Columns["ShiftDuration"].DefaultCellStyle.Format = "HH:mm:ss";
Reference:
https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx
Microsoft suggest to use CellFormatting event
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// If the column is the ShiftDuration column, check the
// value.
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "ShiftDuration")
{
ShortFormDateFormat(e);
}
}
private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting)
{
if (formatting.Value != null)
{
try
{
DateTime theDate = DateTime.Parse(formatting.Value.ToString());
String dateString = theDate.toString("hh:mm:ss tt");
formatting.Value = dateString;
formatting.FormattingApplied = true;
}
catch (FormatException)
{
// Set to false in case there are other handlers interested trying to
// format this DataGridViewCellFormattingEventArgs instance.
formatting.FormattingApplied = false;
}
}
}
I am trying to have this output in my label
example:April 20,2016
but I get 4/20/2016:1200:00:AM instead
I tried to modified it but can't figure this error out
no overload for method takes 1 arguments
cause by this code
lblDate.Text = rdr.GetValue(4).ToString("MMMM d,yyyy");
This is the entire code.
private void GetData()
{
SqlConnection con = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
con.Open();
SqlCommand cmd = new SqlCommand(#"SELECT orderProdName,orderProdType,orderQuantity,orderStatus,orderDateOrdered
FROM orders2
WHERE orderCustomer='"+DropDownList1.SelectedItem.Value.ToString()+"'",con);
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
lblProdName.Text = rdr.GetValue(0).ToString();
lblProdType.Text = rdr.GetValue(1).ToString();
lblQuantity.Text = rdr.GetValue(2).ToString();
lblStatus.Text = rdr.GetValue(3).ToString();
lblDate.Text = rdr.GetValue(4).ToString("MMMM d,yyyy");
}
}
con.Close();
}
The problem is that you are using the Object.ToString() method. This method, does not have arguments. If you want to convert it into a date, you might try this:
DateTime dt = DateTime.Parse(rdr.GetValue(4).ToString())
lblDate.Text = dt.ToString("MMMM d,yyyy");
Edit:
Please note, that if the date column in your database contains null-values, the parse methode will throw an exception. So testing for null is mandatory.
String s = Convert.ToString(rdr.GetValue(4));
if(!String.IsNullOrEmpty(s))
{
DateTime dt = DateTime.Parse(s);
lblDate.Text = dt.ToString("MMMM d,yyyy");
}
The rdr.GetValue(int32) method returns an object and not DateTime.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getvalue(v=vs.110).aspx
Parse your the returned value into a DateTime object and then use the ToString method.
That will work only for DateTime value, you can convert the value in DateTime first:
lblDate.Text = Convert.ToDateTime(rdr.GetValue(4)).ToString("MMMM d,yyyy");
I have the following form:
once I click button Its working like this , all above parameters pass to GetData method
protected void btnShow_Click(object Sender, EventArgs e)
{
ShowReport();
}
private void ShowReport()
{
//Reset
ReportViewer1.Reset();
//DataSource
DataTable dt = GetData(type.Text, category.Text,subsidary.Text,country.Text, DateTime.Parse(date.Text));
............................
}
this is GetData method
private DataTable GetData(string type, string category, string country, string subsidary, string dateHERE)
{
// date = date.Value.ToOADate();
DateTime? mydate = null;
DateTime date2;
bool check = DateTime.TryParse(dateHERE, out date2);
if (check)
{
mydate = date2;
}
DataTable dt = new DataTable();
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["AB_ReportEntities"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("FindIncomplete_Products", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#type", SqlDbType.NVarChar).Value = type;
cmd.Parameters.Add("#category", SqlDbType.NVarChar).Value = category;
cmd.Parameters.Add("#country", SqlDbType.NVarChar).Value = country;
cmd.Parameters.Add("#subsidary", SqlDbType.NVarChar).Value = subsidary;
cmd.Parameters.Add("#date", SqlDbType.Date).Value = mydate;
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
}
return dt;
}
I cannot get result when Date field has null values in above form , I'm getting the following error:
System.FormatException: String was not recognized as a valid DateTime.
Change your method like this:
private DataTable GetData(string type, string category, string country, string subsidary,string date)
{
DateTime? mydate = null;
DateTime date2;
bool check = DateTime.TryParse(date, out date2);
if (check)
{
mydate = date2;
}
}
And then call it like this:
DataTable dt = GetData(type.Text, category.Text,subsidary.Text,country.Text, date.Text);
Obviously passing a value that cannot be parsed to a DateTime will throw an exception using DateTime.Parse so use DateTime.TryParse instead:
The DateTime.TryParse(String, DateTime) method is similar to the DateTime.Parse(String) method, except that the TryParse(String, DateTime) method does not throw an exception if the conversion fails.
Source: DateTime.TryParse
example usage:
DateTime d2;
bool success = DateTime.TryParse(date.Text, out d2);
//if successful, d2 will be set to the value of the string.
You can use this extension:
public static DateTime? TryGetDateTime(this string item, IFormatProvider provider = null)
{
if (provider == null) provider = CultureInfo.CurrentCulture;
DateTime dt;
bool success = DateTime.TryParse(item, provider, DateTimeStyles.None, out dt);
if (success) return dt;
return null;
}
Then change your method call in this way:
DataTable dt = GetData(type.Text,
category.Text,
subsidary.Text,
country.Text,
date.Text.TryGetDateTime());
I have a string date in database. I did like below mentioned format but it shows error like
input string was not in a correct format
But when I referred with internet this method is correct but it does not work for me. Let me know the reason?
string str1 = "select todate from Employee where EmpCode='" + code + "'";
SqlDataReader dr1 = conn.query(str1);
if (dr1.Read())
{
string todate1 = dr1[0].ToString();
int todate2 =Convert.ToInt32(todate1);
}
It sounds like you should be using a DateTime column in the database, at which point there's no need for integers or strings:
var today = DateTime.Today; // Or maybe use DateTime.Now
// Use parameterized SQL rather than string concatenations
string sql = "select todate from Employee where EmpCode=#EmpCode";
using (var conn = new SqlConnection(...))
{
conn.Open();
using (var command = new SqlCommand(sql, conn))
{
command.Parameters.Add("#EmpCode", SqlDbType.VarChar).Value = code;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
DateTime date = reader.GetDateTime(0);
if (today > date)
{
// Do something
}
}
}
}
}
If your date really is being stored as a string and you can't change that (and if you can, then definitely do so), you can use DateTime.ParseExact instead:
// Other code as before
while (reader.Read())
{
DateTime date = DateTime.ParseExact(reader.GetString(0),
"yyyy-MM-dd", // Or whatever the format is
CultureInfo.InvariantCulture);
if (today > date)
{
// Do something
}
}
Note that in both cases, this uses the system local time zone. You may want to consider storing all values in UTC, and performing all calculations that was as well - in which case you can use DateTime.UtcNow.