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
Related
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")
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 date in format 2013-08-05 12:45:56. But I want to store this in format 2013-08-05 00:00:00 in database.
The thing I want is, I don't want to save the time in database.
I am using:
cmd.Parameters.AddWithValue("#VoucherDate", VoucherDate.Date);
But still it is saving the time. Any suggestions?
If you're using SQL 2008 or above, then you can use the Date data type
http://msdn.microsoft.com/en-us/library/bb675168.aspx
If you want to get the Date part only in C#, then you can use the Date property e.g.
var fullDate = DateTime.Now;
var dateOnly = fullDate.Date;
But, if you're only looking to store the date portion, then consider changing the SQL datatype.
Use the date column type instead of datetime
http://technet.microsoft.com/en-us/library/bb630352.aspx
Even you have Date, or DateTime column in database, when you read data back to your program you can format the display date by giving correct DataTime format string.
like dt.ToString("yyyy-MM-dd) , then you will not get any time as output
Once I too had a similar problem, with the help of this answer I fixed it.
Your C# code:
cmd.Parameters.AddWithValue("VoucherDate", VoucherDate.Date);
Tune your SQL query like below mentioned,
DATEADD(dd, 0, DATEDIFF(dd, 0, #VoucherDate))
Try using:
VoucherDate.Date.ToShortDateString();
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 :)
I want to get records from sql server 2005 in datetime format like this "dd/mm/yyyy h:m:s"
My database date is default datetime format
AttLogId int
...
DownloadLog datetime
I am trying to retrieve the datetime like this:
SELECT AttLogId ,convert(varchar,DownloadLogDate,103) FROM AttLog
ORDER BY DownloadLogDate
but I only get the date and not the time.
I suggest you don't try to get the values in a particular string format. Fetch them as DateTime values and then format them in the .NET code using DateTime.ToString("dd/MM/yyyy H:m:s").
It's almost always worth keeping data in its "natural" data type (date/time here) for as long as possible, only converting to text when you really need to. So your SQL should just be:
SELECT AttLogId, DownloadLogDate FROM AttLog
ORDER BY DownloadLogDate
How you then retrieve the data will depend on how you're talking to SQL (e.g. LINQ to SQL, using SqlDbReader etc). But you should be able to get it as a DateTime and then format it locally. This will make it easier to test, easier to debug, give you more control over cultural aspects (date separators, possibly specifying a standard specifier instead of a custom one, etc).
it is because you are using 103 , so it will give only date .
if you want more format check this :
http://msdn.microsoft.com/en-us/library/ms187928.aspx
According to need, u can try this
SELECT AttLogId , convert(varchar(10),DownloadLogDate,103) +' '+ convert(varchar(8),DownloadLogDate,108) FROM AttLog ORDER BY DownloadLogDate
Note : firstone is for date and second one is for time in H:M:S
hope this help u..