I'm trying to insert a datetime value to my database. I'm using entity framework with ASP.NET MVC 4 and SQL server.
using (dc = new GateEntities())
{
tblSite site = new tblSite();
site.CalledInAt = DateTime.Parse("19/09/2013 00:29 AM", new CultureInfo("en- US", false));
dc.tblSites.Add(site);
dc.SaveChanges();
}
When I try to save the data I get the error:
"The value '19/09/2013 00:29 AM' is not valid for CalledInAt."
I also tried Convert.ToDateTime() but no use.
This works fine in my local machine. It's not working only on my shared hosting server.
There are two errors in the code you list.
The first (which I guess is an error introduced while typing the question) is that your CultureInfo is being set to 'en- US' which should be 'en-US'
The other is that US dates are formatted Month then Day and in your string that would make the date you are setting the 19th month of the year.
This code below works for your date value...
DateTime.Parse("09/19/2013 00:29 AM", new System.Globalization.CultureInfo("en-US", false));
The exception is caused by EF's validation which happens in a culture that has a different date format than the string 19/09/2013 00:29 AM.
When it comes to assigning values to entity properties from user input, the best approach is to make sure that you are independent of UI culture. This means that in the UI (probably a view model) you have to capture user input and convert it to a DateTime value. Then you just assign the DateTime value to site.CalledInAt.
Another option is to include the UI culture in the view model and use it to do the conversion in the controller.
I set the culture in web.config and it started working.
<globalization uiCulture="en" culture="en-GB" />
Related
I wanted to save only date in my database. There is a table which holds dates in database and the column which holds date in type of "Date". Now I want to store date from UI,so I placed WPF DatePicker in UI which allows to select date, but whenever I try to get the data from datepicker it shows the date and time.But I want just the dates to be stored in database.
This is the thing i am doing. It is demo code by the way. Can t upload original code. But this explains the thing. you can see in the message box, it shows 14-10-2015 00:00:00 , i want this zeros to be removed.
The dateTime Picker has a property DisplayDate of Type DateTime. This type contains date and time information.
Just use picker.DisplayDate.Date this returns a DateTime value with the TimeOfDay component set to 00:00.00
Edit
Usually you use an SQL Statement to insert or update values in the database. You should use a parametrized SQL statement with an parameter of type DateTime. The SQL API will take care of the conversion form DateTime (.Net type) to your SQL Date type and strip all time information away. It is a good idea to set the time component to 00:00:00 however to avoid any strange "roundings".
Use ToShortDateString() at the end something like:
var date = datePicker.SelectedDate.Value.Date.ToShortDateString();
MessageBox.Show(date.ToString());
I have a SQL Server 2012 Express database that has been installed on a server in Germany. I created a database and have now realised the date formats are incorrect. I need to show each date as dd/mm/yyyy.
When I run dbcc useroptions (after making some changes to the server), I get the following -
language dateformat
-------------------------
British dmy
When I run select GetDate() in a new query, it shows the date as follows -
2014-08-28 13:53:10.550
The bottom line issue is when I enter 28/08/2014 in to a textbox on a web forms project, it errors
String was not recognized as a valid DateTime.
selP.StartDate = Convert.ToDateTime(tbStartDate.Text);
Any ideas why this is happening? I have created a new user since changing the settings to British and dmy, which still produces the same error.
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. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.
The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.
The ISO-8601 format is supported by SQL Server comes in two flavors:
YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!
or:
YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.
This is valid for SQL Server 2000 and newer.
If you use SQL Server 2008 or newer and the DATE datatype (only DATE - not DATETIME!), then you can indeed also use the YYYY-MM-DD format and that will work, too, with any settings in your SQL Server.
Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.
The recommendation for SQL Server 2008 and newer is to use DATE if you only need the date portion, and DATETIME2(n) when you need both date and time. You should try to start phasing out the DATETIME datatype if ever possible
The proper way to achieve that is to set the culture of your web application.
How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization
IN SQL, you need to cast that string as a DATETIME before inserting or updating the database.
CAST('28/08/2014' AS DATETIME)
You can change the format a date is displayed in using the CONVERT. For example, the following will display the date in UK short format (dd/mm/yyyy)
SELECT CONVERT(varchar(50), GetDate(), 103)
If you are doing this in C#, you need to detect the local culture and cast the string to a datetime as approporate.
//You can set the culture on the current thread:
Thread.CurrentThread.CurrentCulture = CultureInfo.InstalledUICulture; // or new CultureInfo("en-GB"); //dd/MM/yyyy
//or you can pass it to the DateTime.Parse method. Something like this:
DateTime startDate = DateTime.Parse(tbStartDate.Text, CultureInfo.InstalledUICulture);
DateTime startDate = DateTime.ParseExact(tbStartDate.Text,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
Actually the GETDATE() function returns the system date and time in the format 'yyyy-mm-dd hh:mi:ss.mmm' irrespective of the Dateformat.Date format for SQL server is in U.S. date format MM/DD/YY, unless a localized version of SQL Server is installed which seems to be the case here.
Use
SET DATEFORMAT <format>
which sets the order of the date parts (month/day/year) for entering datetime or smalldatetime data. Valid parameters include mdy, dmy, ymd, ydm, myd, and dym. The U.S. English default is mdy.
This method allows you use a date format for dates sent to SQL Server of d/m/y, but it is connection dependent. If a new connection is made to SQL Server or if the server is stopped and restarted, the date format will go back to dmy which is default in your case.
selP.StartDate=tbStartDate.Text.ToString("dd/MM/yyyy")
SELECT CONVERT(varchar(50), GetDate(), 103)
SELECT CONVERT(varchar(50), JoiningDate, 103)from Employee where EmpId='1001'
I have an application that use sqlite as local database, but I have problems with the format of the dates.
I am using System.Data.Sqlite as database provider and I create my edmx, that is created from the sqlite database.
When I make a query to the database, in my entity class that has some date field, I can see that the dateTime property has the correct format, in my case, dd mm yyyy and 18:00 (the hour is of 24 hours, not 12pm for example).
However, when I do the binding (I am using WPF and MVVM) to the dataGrid, in the columns of date the format of the date is mm dd yyyy 12pm (the hour is not of 24).
Why?, if I receive the data in the correct format, because the entity object has de date in the correct format I see the information in other format in the dataGrid? When I use SQL Server as dataBase, I don't have this problem, the format is correct in the dataGrid.
My windows is configurated to ES (Spain).
Thanks.
Use can use this xaml
Binding="{Binding MyColumn, StringFormat=MM/dd/yyyy}"
Use this code in DataGridTextColumn tag.
This is a sample code.
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn
Header="MyHeader"
Width="Size"
Binding="{Binding MyDateColumn, StringFormat=MM/dd/yyyy}" />
</sdk:DataGrid.Columns>
I would guess that the problem is with the DateTime.Kind property. Dates can be Local, UTC, or unknown. Check that the date is restoring from the database with the same Kind-ness, and if not, adjust your Sqlite connection parameters to use the Kind you wish to work with.
The proper way to handle this, in my opinion, is to always store dates/times as UTC in the database and always query against the database using equivalent UTC representation. You can set the DateTime kind to UTC in the Sqlite connection settings. You can ensure that your objects have local times in your property setter if you want the objects to always represent times that way, like so:
public DateTime YourDateTimeProperty
{
get { return _dateTime; }
set { _dateTime = value.ToLocalTime(); }
}
Which should ensure that times stay local after being loaded from the database.
Recently I decided to move to another server. Now my application runs on different servers with different culture (IT and EN).
Everything worked fine but now i am facing many problems with date and numbers.
The main problem seems to be SQL Server. In fact, SQL SERVER throws errors.
I solved the problem with date using the method ParseExact:
e.Command.Parameters["#Expiry"].Value =
DateTime.ParseExact("31/12/2099", "dd/MM/yyyy", null);
For decimal numbers i have to swap "." and "," (depending of the culture) if i want the application to work:
Latitude.Value = Latitude.Value.Replace(".", ","); //ONLY for ITALIAN CULTURE
e.Command.Parameters["#Latitude"].Value = Latitude.Value;
I repeat: the errors are generated by SqlServer.
Is there any way to set the culture once for all?
PS: the EN server is GoDaddy Hosting.
UPDATE:
The problem is pure Sql Server.
In fact, checking on my servers, I found a ',' on the first one and a '.' on the second one as separators for money and decimals.I found:
ALTER LOGIN 'MYDBLOGIN' WITH DEFAULT_LANGUAGE = Italian; GO
With the previous query i was able to change the culture on sql server. However, the problem is still there.
What does this return?
select ##LANGID, ##LANGUAGE
If it says Italian,
set language us_english
(or whatever...)
Rather than every time changing the SQL server culture why don't you use
Convert.ToDecimal(Latitude, CultureInfo.InvariantCulture);
DateTime myDate;
DateTime.TryParse(yourdate, new CultureInfo("en-US"), DateTimeStyles.None, out myDate);
Or
DateTime datet1=new DateTime(2012,5,1);
string startdate = datet1.ToString("d", DateTimeFormatInfo.InvariantInfo);
You can change your database Collate:
ALTER DATABASE test2 -- put your database name here
COLLATE Latin1_General_CS_AS -- replace with whatever collation you need
Your problem is not of sqlserver, you make you modifed in your code while inserting/fetching datetime according to the CultureInfo
I had problem in inserting datetime values to sqlite database in C#. Later i found a way to do it. Now i can insert DateTime values by formatting them like this
data.Add("sayacTarihZamani", string.Format("{0:u}", MydateTimeData));
I can see that data is inserted to the database table correctly using a sqlite admin tool.
When i query this data the values which come are wrong. The values are 3 hours later then its normal value.
For example in admin tool i see 30.03.2011 16:00:00 value but in C# grid the value is 30.03.2011 19:00:00 ..
There is one exception to this. I manually entered a row using the admin tool. It's date value is
30.03.2011 11:30:00 in datagrid it is still 30.03.2011 11:30:00 (true)
How can i correctly insert and query the datetime data using sqlite and C#.
Thank you for your time,
Ferda
When you use the u specifier, your DateTime is automatically converted to universal time. From the docs (emphasis mine):
The "U" standard format specifier represents a custom date and time
format string that is defined by a specified culture's
DateTimeFormatInfo.FullDateTimePattern property. The pattern is the
same as the "F" pattern. However, the DateTime value is automatically
converted to UTC before it is formatted.
Try using the F pattern instead if you want to store the local time.
data.Add("sayacTarihZamani", string.Format("{0:yyyy-MM-dd HH:mm:ss}", mydatetime));
worked all right.
Thank you for your help
Ferda