Change date format in asp.net - c#

I have a table which stores dates of an event.I display the dates in a few labels.Everything works fine.BUT i want to display my dates in the format 'dd-mm-yyyy' and the date is stored in sql server as 'mm/dd/yyyy'.
Create table testDate
(
EventStart date
EventEnd date
)
The dates come from datepicker and i dont want to format my dates in datepicker because it gives me conversion problems. I want to change the format when i display the date in asp.net Label.
Right now i dsiplay the date as below :
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from testdate", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
DateTime Received;
DateTime.TryParse(rdr["EventStart"].ToString(),CultureInfo.InvariantCulture,DateTimeStyles.None, out Received);
Label1.Text = Received.ToShortDateString();
}
}
}
Thanks in advance.

You don't need to parse it anyway. SQL Server saves DateTime in a binary format. It doesn't have any format. Format concept only an issue when you get their textual representation.
Just cast it to DateTime (which is date mapped with DateTime in CLR side) and use custom date and time format specifiers to get it's string representation with which format you want.
Label1.Text = ((DateTime)rdr["EventStart"]).ToString("dd-MM-yyyy");
By the way, I strongly suspect you need to use month instead of minutes. That's why you need to change your mm part to MM. mm specifier is for minutes and MM specifier is for months.
Use using statement to dispose your SqlCommand and SqlDataReader objects like you did your connection.
Do not use select * by the way. It is kind of bad practice.

Related

Comparing two datetimes to check for a clash but seems to be confusing MM/DD with DD/MM C# ASP.NET

I am trying to check my database for a clash, I am reading up using a reader and calling the value down. My value is 10/12/2018 15:00:00 So I have stored this as #moduleStartTime
My next query checks the database using the above datetime and if it is between any other dates entered.
The issue I am encountering is that there are no clashes, so this shouldn't flag up that there are. I have found that the clash it is returning has a datetime of 12/10/2018 15:00:00
It appears as though somewhere in the search, it is reversing DD/MM
Here is my code
//Reading to get all modules student is enrolled on
string checkclash = "SELECT * FROM cModuleTimes INNER JOIN cStudentModule ON cModuleTimes.ModuleID = cStudentModule.ModuleID WHERE cStudentModule.StudentID=#studentid AND #date BETWEEN[StartTime] AND[EndTime] AND ModTimeID <> #modtimeid";
SqlCommand myCommandclash = new SqlCommand(checkclash, myConnectionclash);
myCommandclash.Parameters.AddWithValue("#date", moduleStartTime);
myCommandclash.Parameters.AddWithValue("#courseid", courseid);
myCommandclash.Parameters.AddWithValue("#studentid", user);
myCommandclash.Parameters.AddWithValue("#modtimeid", moduletocompareid);
//create a sqldatareader object that asks for dats from a table
SqlDataReader rdrreadclash = myCommandclash.ExecuteReader();
if (rdrreadclash.HasRows)
{
while (rdrreadclash.Read())
{
string getname = rdrreadclash["ModTimeID"].ToString();
string gettime = rdrreadclash["StartTime"].ToString();
Warning.Text = "There appears to be a clash with this event..<br><br> <br> <b>Would you like to continue?</b> <br><br>";
}
ViewClash.Visible = true;
YesContinue.Visible = true;
FinishMod.Visible = false;
}
myConnectionclash.Close();
I have tried a couple of conversions but am receiving an issue with string not recognised as a DateTime.
If anyone has any answers on how I would prevent this clash from appearing, I would be very grateful.
Thank you.
moduleDateTime is currently a string, you need to parse it in to a DateTime object where the parsing operation has the proper MM/DD order you want.
DateTime dateAsDateTime = DateTime.ParseExact(moduleStartTime, "dd/MM/yyyy HH:mm:ss", null);
myCommandclash.Parameters.AddWithValue("#date", dateAsDateTime);
You then must format the returned date time back to a string in the format you want.
string gettime = ((DateTime)rdrreadclash["StartTime"]).ToString("dd/MM/yyyy HH:mm:ss ");

inserting a string that looks like a date to a database date column [duplicate]

This question already has answers here:
Converting dd/mm/yyyy formatted string to Datetime [duplicate]
(3 answers)
Closed 6 years ago.
im having a problam inserting a string that looks like a date (23.02.2015)
from datagridview to my local database date column that .
i know i need to transfer my string "23.02.2015" to 23/02/2015 and convert it to a date variable before im inserting it to my database date column but i dont know how to do it inside my code :
private void button3_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string constring = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\john\Documents\Visual Studio 2015\Projects\Project\Project\DB.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO ResultsTable VALUES(#Date, #TagNumber)", con))
{
cmd.Parameters.AddWithValue("#Date", row.Cells["Exposure Date"].Value);
cmd.Parameters.AddWithValue("#TagNumber", row.Cells["Device #"].Value);
cmd.ExecuteNonQuery();
}
}
}
MessageBox.Show("Records inserted.");
}
in short - im having a problam to convert a string like "23.05.2014" to a date type like 23/05/2014 to insert it to date column in my database in my code .
This might do the trick for you if your string date is always in the given format. DateTime.ParseExact Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
string smdt = row.Cells["Exposure Date"].Value;
//This is the string format which is going to parse the Date
string format = "dd.MM.yyyy";
DateTime dt = DateTime.ParseExact(smdt, format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
and then
cmd.Parameters.AddWithValue("#Date", dt);
Please try below code:
string stringDate = "23.02.2015"; // Hold your string date here (row.Cells["Exposure Date"].Value)
DateTime date = DateTime.ParseExact(stringDate, "dd.MM.yyyy", CultureInfo.InvariantCulture);
This will convert your string date (stringDate) to a datetime (date) object, and you can pass this date object to stored procedure parameter.
I believe, you are always getting string date in this ("dd.MM.yyyy") format. Else, you will need to change it as per your string format.
Please let me know if this helps.

Unable to convert textbox(dd/MM/yyyy) date to datetime format

I have a database date "2014-11-26". I have a calender with format(dd-MM-yyyy) I am trying to bring some values to my form from databse by textbox selected date
protected void txtdate_TextChanged(object sender, EventArgs e)
{
//DateTime timeIn = Convert.ToDateTime(txtdate.Text);
// DateTime time1 = DateTime.ParseExact(txtdate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
str = "select TimeIn,TimeOut from MusterRoll where EmpCode='" + ddcode.SelectedItem.Text + "' and Date='"+time1+"'";
dr = conn.query(str);
if (dr.Read())
{
DateTime time = dr.GetDateTime(0);
TimeSelector1.SetTime(time.Hour, time.Minute, TimeSelector1.AmPm);
DateTime time2 = dr.GetDateTime(1);
TimeSelector2.SetTime(time2.Hour, time2.Minute, TimeSelector2.AmPm);
}
}
The problem is databse date format and my calender format is different. I tried two methods(which I placed in command line)but shows error message like "input string was not in correct format". I surfed internet and find these same answers. May I know why it shows error?? i am trying to make database dateformat and calender format as same
First of all, a DateTime doesn't have any implicit format. It has just date and time values. String representations of them can have a format.
I strongly suspect you save your DateTime values with their string representations which is a horrible idea. Read: Bad habits to kick : choosing the wrong data type Pass your DateTime values directly to your parameterized queries instead of their string representations. Anyway..
For;
DateTime timeIn = Convert.ToDateTime(txtdate.Text);
Convert.ToDateTime(string) method uses DateTime.Parse method with your CurrentCulture settings. That means if your string isn't a standard date and time format of your CurrentCulture your code throws FormatException. I guess dd-MM-yyyy is not a standard date and time format of your CurrentCulture.
For;
DateTime time1 = DateTime.ParseExact(txtdate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
When you use DateTime.ParseExact, your string and format should match exactly.
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case; they are not ("26-11-2014" and "yyyy-MM-dd"). Use dd-MM-yyyy format instead.
DateTime time1 = DateTime.ParseExact(txtdate.Text,
"dd-MM-yyyy",
CultureInfo.InvariantCulture);
Then you can generate the format from your time1 like;
time1.ToString("yyyy-MM-dd"); // A string formatted as 2014-11-26
For your command part, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
You can use this
var dateAndTime=Convert.ToDateTime(Txttradedate.Text).ToString("ddmmyyyy");

how can we change the date format of SQL Server(2008) Database?

For data saved via win form, the input date format is(dd/mm/yyyy). The database showsin (yyyy-mm-dd) format. How can I change date format?
private void btnAllocate_Click(object sender, EventArgs e)
{
for (int i = 0; i < dgvDetails.Rows.Count; i++)
{
SqlConnection con = new SqlConnection("server=HP-HP; database=Restaurent; user id=sa; password=sql2008");
SqlCommand cmd = new SqlCommand("INSERT INTO WtrTblAllot (WtrNm,Type,No,currDate) values (#WtrNm,#Type,#No,#currDate)", con);
cmd.Parameters.AddWithValue("#WtrNm", dgvDetails.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Type", dgvDetails.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#No", dgvDetails.Rows[i].Cells[2].Value);
cmd.Parameters.AddWithValue("#currDate", dtTmPkr.Value);
con.Open();
cmd.ExecuteNonQuery();
cmd = null;
}
MessageBox.Show("Added successfully!");
}
date time piker (dtTmPkr) format (dd/mm/yyyy)
SQL Server doesn't store a DateTime in any string format - it's stored as an 8 byte numerical value.
The various settings (language, date format) only influence how the DateTime is shown to you in SQL Server Management Studio - or how it is parsed when you attempt to convert a string to a DateTime.
There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT.
So really, it's not about changing the date format in SQL Server - it's about how to format and display a Datetime that you retrieve from SQL Server. Use the appropriate T-SQL CONVERT parameters, or format the DateTime in your C# front-end code
Update: if you're inserting the value from the DateTimePicker into SQL Server using your query shown in the question, you should be just fine - it's inserting a DateTime parameter so you won't have any issues with string formatting of your dates.
When you need to convert a DATETIME in SQL Server to a specific format - use
SELECT CONVERT(VARCHAR(50), YourDateColumn, 103)
and this will give you a date in dd/mm/yyyy (British/French) format. If you need a different format - use a different style (some other number than 103). Those styles are very well documented here.
If you read back the DateTime column into C# and you need to format it, then use
string formatted = YourDateTime.ToString("dd/MM/yyyy");
to get the values you need. Watch out: to format the month, use MM (capitalized!) because the mm would format the minutes of your DateTime instead.
try to parse the Date to datetime object in c# prior to adding in Parameter.
DateTime Dt = DateTime.ParseExact(dtTmPkr.Value, "dd/MM/yyyy", CultureInfo.InvariantCulture);
cmd.Parameters.AddWithValue("#currDate", Dt);
Use this :
SqlCommand cmd = new SqlCommand("INSERT INTO WtrTblAllot (WtrNm,Type,No,currDate) values (#WtrNm,#Type,#No,CONVERT(CHAR(10), #currDate, 103))", con);

Error on & after 13th of Every Month; When Converting Date and/or Time from character string

The code below Works ok; from 01st to 12th of every month; However as soon as I click on 13th or greater date I Get this error
Conversion failed when converting date and/or time from character string.
This my Code
DateTime dt = Convert.ToDateTime(Calendar1.SelectedDate.ToString("yyyy-MM-dd"));
myConnection.Open();
string cmdStr1 = "SELECT COUNT(*) FROM Payment WHERE PaymentDate = '" + dt + "'";
SqlCommand PIDexist1 = new SqlCommand(cmdStr1, myConnection);
int temp1 = Convert.ToInt32(PIDexist1.ExecuteScalar().ToString());
myConnection.Close();
Thank for your Help
This is How Date is saved in my Database 2012-01-13
No, never bind dates like that. Let the .NET data provider handle this for you - there are just way too many pitfalls with locales on the App and Sql Server for you to use strings as dates.
myConnection.Open();
string cmdStr1 = "SELECT COUNT(*) FROM Payment WHERE PaymentDate = #dt'";
SqlCommand PIDexist1 = new SqlCommand(cmdStr1, myConnection);
SqlParameter parameter = PIDexist1.Parameters.Add("#dt", System.Data.SqlDbType.DateTime);
parameter.Value = dt;
...
Because it's trying to convert 13 as the month.
Try using DateTime.Parse("...", [Culture]) and specifying the appropriate culture.
Most likely you're encountering a DD-MM-YY vs MM-DD-YY situation. It's too much of a coincidence that it works until the 12th day when there are 12 months. Try to be more explicit in your use of dates; perhaps use the three letter month code.
There is no need to convert the date .ToString(). Simply use the SelectedDate DateTime value as named parameter to the SqlCommand query. If you need the day only, use the DateTime.Date property

Categories

Resources