Changing the format of DATETIME property in winform C# - c#

What's wrong with this code?
Client c = new Client();
string format = "yyyy/MM/dd HH:mm:ss";
string dateAdded = now.ToString(format);
c.RegistrationDate = DateTime.Parse(dateAdded);
c.RegistrationDate is a dateTime object in the client class and I want it to insert to my database.
However It doesn't convert the freaking date to the format in my mysql database. It always says that string format is incorrect. WHAT have i done wrong???? should I convert my Registration Date to string??? Thanks
**EDIT: Sorry I've forgot to mention. "now" is now = DateTime.Now; it gets the current time of the date and time.

A DateTime doesnt have a format - it's just the date/time. (Whether it's local time, UTC or whatever is a different matter, mind you.)
Firstly, you shouldn't be converting to and from text like you are: that's just a recipe for trouble. Just use:
c.RegistrationDate = now;
... performing any rounding you need to.
You haven't shown how you're trying to insert the value into your database. If you're including the value in the SQL statement directly, that would explain it. You should be using a parameterized SQL statement and passing the value directly in the parameter - no conversion necessary.
If you're already doing that, please show us the code you're trying to use to insert the data, and we'll see what we can do. See the documentation for some examples.

I don't think there is anything wrong with the c# code,except I assume you must be doing
string dateAdded = DateTime.Now.ToString(format);
Otherwise I am not sure what 'now' is.

Related

Convert datetime to specific format from datatable

I want to convert date time value from datatable to only show time value.
I have below code to make this convert process;
DateTime ST = DateTime.ParseExact(dtPivot.Rows[e.DataRow][0].ToString(), "HH:mm:ss",CultureInfo.InvariantCulture);
ulbTime.Text = ST.ToString("HH:mm:ss");
However this throws an error
String was not recognized as a valid DateTime
I searched however couldn't find a solution for me.
How can I solve this ?
Your question asks how to show it so use String.Format to show the time portion
DateTime ST = Convert.ToDateTime(dtPivot.Rows[e.DataRow][0]);
var t = string.Format("{0:hh:mm}",ST);
You shouldn't need to parse, since the entry being pulled from the database should already be a DateTime field. So in theory, you should be able to pull the data in the following.
var model = IDbConnection.Query(query);
var time = model.First().Date.ToString("hh:mm:ss");
So if you're using a object relational mapper, such as Dapper your model has a DateTime for the object, then you use the string formatter to do the time.
You could also do:
var time = model.First().TimeOfDay();
Built directly into the DateTime is a time of day, works similar to a date short hand method. You could obviously use a DateReader or DataTable accessing the column information index, with a ToString("hh:mm:ss") to return the time specifically. But, you can't do ToString in some instances, because a DBNull.Value or invalid value will cause a reference exception. So you'll need to sanitize and ensure those odd values can't be passed.
I prefer the above, because the mapper should associate the value based on your defined type. So you don't need any extra casting or converting.

How to format a Date into SQL server using EntityFramework

I'm trying to storage into my database ONLY the DATE not DATE AND TIME, only Date, but it always came with the time together.
This is how I do to storage only the date inside of String :
string.Format("{0:dd/MM/yyyy}", DateTime.Now)
And works fine, but now, I want to storage a StringDate to a Date in my SQL Server database. So I did this :
EntityTable...
[Column(TypeName = "date")]
public DateTime? InicialDate { get; set; }
Controller
InicialDate = DateTime.ParseExact("01-12-2016",
"dd/MM/yyyy",
new CultureInfo("pt-BR"));
And inside of my Table, the Date is not at the right format as I expected, I came like this :
2017-12-01 and not, DAY-MONTH-YEAR....
And if I try to make a query and retrieve the date, i came like this :
"InicialDate": "2017-12-01T00:00:00"
I just want to save ONLY the DATE without time!
Correct way is creating your Date type for using whole project. Also there is some Data class already developed: https://github.com/claycephas/csharp-date
If you've already created the table with [Column(TypeName = "date")], please check the schema and data of the table, the type of column InicialDate should be date, which doesn't save the time portion of datetime.
The time portion you saw in the result (i.e. T00:00:00) was appended by EF, when it was cast to DateTime structure.
DateTime is internally just a single number (probably an int/long, representing the number of seconds since the Epoch; not sure about this, though; but it doesn't really matter here) and how it's displayed as a string depends on the format used. DateTime.ParseExact("01-12-2016", "dd/MM/yyyy", new CultureInfo("pt-BR")); parses the date into DateTime internal representation according to the pt-BR rules for displaying date, then when EF is posting this to the db it converts the internal representation to ISO-8601 textual form (because SQL is text-based), then the db engine again converts it into a number form and stores it. When you look in the db, you see it as 2017-12-01, because the tool you use to do this is set up to display dates in the ISO-8601 format.
So, the date is stored correctly, what you seed depends on the format the particular app uses to display dates.
Change DateTime to nvarchar(10) in database if u use DateTime in database 00.00.00 will be automatically assigned by database. So, you are getting time with it while retrieving.
Change column datatype to Varchar issue will be resolved.
Sincerely,
Thiyagu Rajendran
**Please mark the replies as answers if they help and unmark if they don't.

Convert date type in c# to match sql server 2008 date type

I have retrieved a date from an application and stored it in a DateTime Variable. The format of date is dd/mm/yyyy.
I now want to update a column (with datatype date (yyyy/mm/dd)) in a sql server 2008 database with this date
I have tried the below code, but it's giving me an exception "string was not recognized as valid datetime". Please help to solve this problem.
DateTime date = calExpirydate.SelectedDate;
DateTime date1 = DateTime.ParseExact(date.ToString(), "YYYY/MM/DD", CultureInfo.InvariantCulture);
You don't need to convert it at all if you use parameters (and you should be).
A rough example:
DateTime date = DateTime.Now;
SqlCommand command = new SqlCommand();
command.CommandText = "INSERT INTO table (date) VALUES (#date)";
command.Parameters.Add("#date",SqlDbType.DateTime).Value = date;
I'm using SQL Server here, however the concept is similar across most ADO.NET providers.
Your DateTime variable in the framework is stored in one basic format. The way it appears is just formatting off of the .ToString. It's saying give me your date bit make it look like this. Sql server is similar, it understands the date time variable regardless of how it appears.
If you pass your DateTime as exactly how it is in the framework it will save it correctly. The date and time isn't changing just how it's displayed. Your try parse isn't working though because it's not able to recognize the partial string you're giving it.
You don't even need a new date time variable to see it the way you want. Even if you're successful you will have identical date time variables.
yyyy/MM/dd should be correct
DateTime string format

issue with date between c# and sql converting

so i have a string "09/15/2014" and in c# it converts it to date:
DateTime from = Convert.ToDateTime(fromdate);
this outputs "9/15/2014" and when I send it over to sql I get this:
select convert(varchar, '9/1/2014 12:00:00 AM', 101)
which doesn't work for me because I need to keep any leading zero's.
help?
If you're worried about the string formats for dates with Sql Server, you're doing it wrong. As a comment to another answer indicates, SQL Server internally stores all dates in a machine-optimized numeric format that is not easily human-readable. It only converts them to a human-understandable format for output in your developer tools.
When sending dates to Sql Server, always use query parameters. In fact, when sending any data, of any type, to Sql Server in an SQL statement, always use query parameters. Anything else will not only result in formatting issues like your problem here, but will also leave you crazy-vulnerable to sql injection attacks. If you find yourself using string manipulation to include data of any type into an SQL string from client code, step away from the keyboard and go ask a real programmer how to do it right. If that sounds insulting, it's because it's so hard to understate the importance of this issue and the need to take it seriously.
When retrieving dates from Sql Server, most of the time you should just select the datetime field. Let client code worry about how to format it. Do you want leading zeros? Great! The Sql Datetime column will at some point be available in C# as a .Net DateTime value, and you can use the DateTime's .ToString() method or other formatting option to convert the value to whatever you want, at the client.
SQL queries use a date and time format which goes like this:
2014-09-15
That's year-month-day. As per the comments below, this may be different depending on the collation you have on your database (see Scott's comment for a more accurate way to describe this and get dates into this format).
DateTime's ToString method has an overload which takes a formatting string. So you can pass the format you want the string to be output to. Try it like this:
string queryDate = from.ToString("yyyy-MM-dd");
And see what you get. Use that on your query.
But if you really want this done right, use parameters. Like:
SqlCommand command = new Command(connection, "SELECT * FROM foo WHERE someDate = #date");
command.Parameters.AddWithValue("#date", from);
// where "from" is your DateTime variable from the code you've shown.
This will save you the trouble of DateTime to String conversions.

Cannot pass date into stored procedure

Trying to pass date into a stored procedure as follows:
#dateRegistered = '28/04/2012'
But it keeps telling me:
Error converting data type varchar to date.
It works if I do it as:
#dateRegistered = '04/28/2012'
But this is not the format I want to use.
I have run the following query to set the format:
SET DATEFORMAT dmy
Why isn't it working?
Edit: Here is how I did it:
In my stored procedure, I put:
SET DATEFORMAT dmy
Then from code, I pass it as:
myCommand.Parameters.Add("#dateRegistered", SqlDbType.Date);
myCommand.Parameters["#dateRegistered"].Value = DateTime.Now.ToString("dd/mm/yyyy");
I passed it as string to ensure that even if my computer (or the server) has a different date format, it will always use dmy.
Edit Edit:
I passed it as datetime.now. It seems to transform it to the default format when I send it, and then transform it back to my computer format when I read it. Unsure how exactly this happens, but it seems to be working fine.
It looks like the parameter is a date (in the database), while you try to pass a string (which corresponds to varchar in the database). If you instead pass a .NET DateTime object it should work as expected.
Save yourself the headache and use an unambiguous date format - 20120428 (YYYYMMDD) or 2012-04-28.
As an aside: you mention you're using C# (based on the tags) - how are you using ADO.NET? Or is it Linq to SQL / EF / some other ORM?
Edit:
Ok, use the CONVERT function with an appropriate parameter indicating the format of your date string
EG:
declare #D datetime
set #D = CONVERT(datetime, '04/28/2012', 101)
print #D
101 is US standard format mm/dd/yyyy.
Using convert will ensure it ALWAYS works regardless of any environment settings such as the date order.
If you call set dateformat dmy, that only affects the current connection. You'd have to set it every time right before you convert the string to a date.
The best solution is probably the ISO format, like #IanYates suggests.
dear your code is working after using
* SET DATEFORMAT dmy
because you are passing date as "dd/MM/yyyy"
like "DateTime.Now.ToString("dd/mm/yyyy")"
check the date format in your database by following command :-
dbcc useroptions
and check "dateformat : mdy" by default. So passing your date in "MM/dd/yyyy" format will also work fine.
Happy Coding :)

Categories