When I get data from Mysql table the datetime column 2017-09-19 16:14:47 will automatically convert into its own format like 9/19/2017 3:45:50 PM. It happens when I'm getting data into DataTable and convert into string as follows:
DataTable update;
localdb.MysqlQuery(queryUpdate);
update = localdb.QueryEx();
if (update.Rows.Count > 0)
{
onlinedb = new DataAccessOnline();
foreach (DataRow row in update.Rows)
{
row["added"].ToString(); //9/19/2017 3:45:50 PM
but I need get this value as it is in TABLE column 2017-09-19 16:14:47 how can I do that ?
First you need to convert the data you get from the DB into a DateTime object using the Convert.ToDateTime method.
Then you can specify the format you want on the DateTime.toString method.
It would look something like this:
DateTime added = Convert.ToDateTime(row["added"].ToString());
string formatted = added.toString("yyyy-MM-dd HH:mm:ss");
You can format it in your server side query as string.
mySql is giving data to C# as datetime type. C# has slightly different format of interpreting and presenting datetime type value to you. Ultimately, data will work like a datetime field anyways.
If you bring it like a formatted string, you would need to convert it to datetime in C# to make it function like a datetime. On the other hand, if you want it to be converted in C# for presentation purposes, do it in C#, not while bringing data because then it would be a string, not datetime.
You can see more .ToString() conversion details here.
Default format you need is "u", but you can provide your own format string like this one.
string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
Related
I have a date stored in SQL. When I get the value back I want to format as MM/dd/yyyy, but I'm getting values like 2020-09-01 instead.
AccountHolderRenewalDate = a.AccountRenewalDate.ToString("MM/dd/yyyy")
Both AccountHolderRenewalDate and a.AccountRenewalDate are strings. a.AccountRenewalDate holds the date I'm after.
What would I be doing wrong here?
This should do the trick - I'm assuming that your DB is a Date column so I didn't use DateTime.TryParse:
DateTime.Parse(AccountHolderRenewalDate).ToString("d");
If you want 09/01 instead of 9/1 use
.ToString("MM/dd/yyyy")
instead
consider me a beginner in c#
I am doing some changes in a pre developed software (C#.Net) , we are saving data by datewise , Currently in insert query (build in c#) we are passing GETDATE() to save today date , but now we have to save data on the basis of a different date.
When I am building query in c# , I m passing that a datetime variable into query
after conversion , conversion as follow
Date_Stamp = DateTime.ParseExact(dt.Rows[0][0].ToString(), "MM/dd/yyyy HH:mm:ss tt", new CultureInfo("en-IN"));
but it is showing error "String was not recognized as a valid DateTime.".
The reason to convert is coz these date field are getting displayed in format ToString("yyyy-MM-dd"));
Which will give 2017-07-13 14:56:30.233 as 13-jul-2017 on front end (as per requirement). We cant change this part of code as it is being used in lot of places , hard to change .
Problem is
variable storing value as
2017-12-07 00:00:00.000
which give after conversion 07-Dec-2017 [wrong - it is needed as 12-jul-2017]
GETDATE storing value as
2017-07-12 14:56:30.233
which is after conversion coming right as 12-jul-2017
I know there is no datetime format in sql server when it come to storing data
But can we store value from variable [2017-12-07 ] as [2017-07-12 ] ?
How GETDATE() give us date in year-month-date format
?
Neither .NET's nor SQL Server's date related type have any format. All of them are binary values, just like integers and decimals. Formats apply only when they are explicitly or implicitly converted to strings, or parsed from strings.
Assuming your query looked something like SELECT GETDATE(), ... and you loaded the results to an DataTable, the values will be returned as DateTime values. If you used a strongly-typed DataTable you could just use the value. With a generic DataTable the value will be boxed and return as an object.
All you have to do is just cast the field value to DateTime :
Date_Stamp = (DateTime)dt.Rows[0][0];
This will also work for date and datetime2 types. datetimeoffset is returned as DateTimeOffset. time is returned as TimeSpan.
The problem in the original is caused because the field value is formatted into a string using the current culture dt.Rows[0][0].ToString() first. Then ParseExact is called trying to parse it using a different format. A simple DateTime.Parse(dt.Rows[0][0].ToString()) would have worked (even though it would be wasteful), since both DateTime.Parse and DateTime.ToString() use the same culture.
UPDATE
Reading date fields from a table has no issues - the values are returned using the appropriate date type. For example, running SELECT StartDate from ThatTable will return DateTime if the table's schema is :
CREATE TABLE ThatTable
(
ID int,
StartDate datetime
)
Problems are caused if, instead of using the correct type, dates are stored as strings in VARCHAR columns. That's a serious bug that needs to be fixed. There is NO assurance that the strings can be parsed to dates at all, or that they follow the same format. It's all too easy for some faulty application code to use eg DateTime.Now.ToString() and store a localized string in there.
Even if the format is the same, it's just wasteful and unreliable. The string takes more storage than the equivalent type, introduces conversion issues, prevents the use of date functions, and the server can't apply date optimizations to queries and indexing.
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
I had written stored procedure which returns date only not datetime i.e
CurrentDate
2013-10-06
So when i stored this result in dataset using da.fill( ) method, there inside the datatable it is stored in the format datetime resulting as 2013-10-06 12:00:00
How to solve this problem?
Thank You all guys, finally i followed this approach
foreach (DataRow dr in dt.Rows)
{
dr["date"] = DateTime.Parse((dr["date"].ToString())).ToShortDateString();
}
Which only returns date without time.
A datetime is always stored with default time value as "12:00:00",u can only format it to your desire format,
ds.Table[0].rows[0][0].tostring("yyyy-MM-dd")
SqlDateTime class may be helpful
You can format the DateTime string to show only Date. Since .NET doesn't have a Date-Only Datatype, you have to filter the Date out of a DateTime object.
Choose the ToShortDateString() Method and if you need a special format, then you have to use the ToString() method and provide a format string which can be found easily if you google for "DateTime Format".
I have a string arranged in a way that would match the format yyyy-dd-MM HH:mm:ss
It might look like this 2010-20-12 13:30:00
I need to insert this into a smalldatetime column in SQL Server. The format of the column is
yyyy-MM-dd HH:mm:ss
I need the string to look like this 2010-12-20 13:30:00 or else SQL Server will get the month and day confused.
Thanks for your thoughts
Don't send your data to SQL server using a string to start with. Instead, use a parameterized SQL statement, and get the driver to do the work for you after you specify a DateTime. (See the SqlCommand.Parameters documentation for an example.)
This is how you should deal with pretty much all values - especially those entered by users. As well as not having to worry about formatting, this will prevent SQL injection attacks.
So that just leaves the task of parsing your input string as a DateTime, which is best done with DateTime.ParseExact or DateTime.TryParseExact, depending on whether you want the result of a parsing failure to be an exception or not.
you can try something like this:
//First convert string to DateTime
DateTime dt;
dt = Convert.ToDateTime("2010-20-12 13:30:00");
//Second Convert DateTime to formatted string
string t_time;
t_time = dt.ToString("yyyy-dd-MM hh:mm tt");
HTH.
You shouldn't need to convert to a string. Use a parameterized sql query or a stored procedure and just provide a datetime object as the parameter. The sql command will handle the insert just fine.
If you only have the string, you can turn it into a datetime using DateTime.Parse and a DateTimeFormatInfo (see this documentation for assistance with creating the format info).