I need to convert datetime2 (getting data from SQL Server) to datetime (like current time) in ASP.NET.
I use this method but it is not working correctly
Convert.ToDateTime(messageVO.MDateTime).ToString("yyyy-MM-dd h:mm tt")
messageVO.MDateTime is getting from database.
How can I do this? Please help me.
You cannot do a conversion since the implicit DateTime2 mapping to .NET data type is to System.DateTime (see http://msdn.microsoft.com/en-us/library/bb675168.aspx). Without seeing your class definition for the type of messageVO, I would expect MDateTime to be of DateTime data type (especially if you're using entity framework) as part of the mapping standards.
Related
So I have 2 types of dates in my db, date (yyyy-mm-dd) and datetimeoffset (yyyy-mm-ddThh:mm:ss.ms+Z), and I was wondering what is the best practice to deal with it when I'm taking the data from the DB and passing it as a json to the UI/mobile.
I used to always parse dates to datetimeoffset so normal dates will be something like 2018-09-24T00:00:00.000+00:00 instead of simply 2018-09-24 but it works perfectly with datetimeoffset that are already saved like that in the DB
In multiple ways you can handle this situation.
1 : From API side always give predefined date format value
Example yyyy-mm-ddThh:mm:ss.ms+Z
And from the client side based on conditions you can convert it.
2: Keep different View models/ Properties may be for storing yyyy-mm-dd you can give string data type and for yyyy-mm-ddThh:mm:ss.ms+Z just DateTime . and based on your db you can write a condition and map the particular data.
3: Keep a single property for returning the date and make it as string
Example : Public string CurrentDate{get;set;} and you can simply map the database values(Conversion should be done). In this case client no need to worry about the date conversions they can simply show what ever you are passing from the api.
Note : The method 3 is not preferable because in the case in some places the user may see yyyy-mm-dd in some other places yyyy-mm-ddThh:mm:ss.ms+Z.
Take a look at SQL Server Data Type Mappings
You will see that SQL Server's Date, DateTime and DateTime2 all map to .Net's DateTime data type,
and DateTimeOffset maps to DateTimeOffset.
SQL Server Database Engine type .NET Framework type
date (SQL Server 2008 and later) DateTime
datetime DateTime
datetime2 (SQL Server 2008 and later) DateTime
datetimeoffset (SQL Server 2008 and later) DateTimeOffset
I've been through a tough day facing this problem. In ent object, I have DiinputTanggal property as Date. In database, I have DiinputTanggal column as DateTime. When I try to insert the ent object into the database, I got the following error shown in the screenshot below. But when I debug, the property DiinputTanggal in ent object seems perfectly fine and nicely formatted. I have no idea where is my mistake.
Looking at your screenshot, it is probably the TaggalAktif property which is causing the overflow. .Net DateTimes default to DateTime.MinValue which cannot be represented in SQL DateTime.
You have several options
Initialize the DateTime to a value supported by Sql DateTime (in the range indicated by the error)
Change the DateTime to be nullable in both the class and database, (and ensure the property is initialized to null).
Use another Sql DataType to store the data e.g. DateTime2 or just Date if time isn't needed.
I have a string like this: 16:00 and I want it to be saved in my SQL Server database in a column which has a data type of time(7)...
Of course, before I save it in there, I need to convert my string in a time data type.
Upon using Convert.ToDateTime, I get an error:
Cannot implicitly convert type 'System.DateTime' to 'System.TimeSpan'
That is because I am saving Convert.ToDateTime(myString) into a property of an entity from my database which has time(7) data type...
Are there other ways of converting my string into a format which is compatible with the time(7) datatype in SQL Server?
The managed type that corresponds to the SQL time data type is TimeSpan (or TimeSpan? when nullable), not DateTime – refer to Mapping CLR Parameter Data for the list of type conversions.
You can use TimeSpan.Parse(myString) to convert your string.
Use SQL Server's Convert function
convert(DateTime, '20:10:00:000', 114);
See CAST & CONVERT
You can also use it like this
Convert.ToDateTime(myString).TimeOfDay();
This will return the time . And you can pass this value to Sql command parameter.
TimeOfDay returns TimeSpan object.
TimeSpan tp = Convert.ToDateTime(myString).TimeOfDay();
Instead of Convert.ToDateTime use DateTime.TryParseExact(yourTimeString, "HH:mm",<other parameters>, out dateTime);
Other parameters are missing. Please look into the DateTime.TryParseExact documentation. But basically it converts your string to dateTime from the format you are specified.
C# code is reading data from database through dynamic queries.
Select ID, TransDate from Table_01
Business logic is processing the data and finally putting back the date into the database again.
INSERT INTO Table_02
( ID,ClosingDate) VALUES
( 1,Convert(DateTime, '27/07/2011 12:00:00 AM',120))
Since date format, i am inserting, is dd/MM/yyyy. Sql Server does not like it and .net throwing this error:-
The conversion of a char data type to a datetime data type resulted in
an out-of-range datetime value
If i change it to MM/dd/yyyy or yyyyMMdd then it works.
But system regional date time settings can be changed any time by any user, so I am looking for some concrete solution.
What is the best way to handle it?
The converstion style 120 is: yyyy-mm-dd hh:mi:ss(24h). Try using 103 (dd/mm/yyyy) instead.
INSERT INTO Table_02
( ID,ClosingDate) VALUES
( 1,Convert(DateTime, '27/07/2011 12:00:00 AM',103))
You can find the documentation for the styles here.
IMO the best way would be to use parameterized query - then the driver / server takes care of converting data into correct format.
Try setting the dateformat and using Cast:
Set DateFormat DMY
GO
INSERT INTO Table_02( ID,ClosingDate)
Select 1, Cast('27/07/2011 12:00:00 AM' As DateTime)
Stick to yyyyMMdd it will always work regardless of regional settings and date format settings. Beware of yyyy-MM-dd, it will not work when date format is DMY. http://www.sommarskog.se/wishlist.html#YYYYMMDD
How does one use the SQL time datatype introduced in SQL Server 2008 in C#.NET?
I've been trying to get it to work but no success.
Here is an MSDN article that reviews all the new Date and Time datatypes introduced in SQL Server 2008 with respect to ADO.NET. As the document says: For System.Data.DbType.Time you would use the .NET Framework type System.TimeSpan
I think you can use TimeSpan datatype for your purpose.
Here is an article that explains the use of Time datatype in ADO.NET.
Also even people from Microsoft tend to recommend mapping the sql datatype time to System.Timestamp I would not recommend doing so,
since the range of sql time is 00:00:00.0000000 - 23:59:59.9999999
wheras the range of System.TimeSpan is 10675199.02:48:05.4775808 - 10675199.02:48:05.4775807
which is just slightly different and can lead to nasty runtime out of range errors.
you can read it using datareader using something similar to following statement .
TimeSpan time = dr.GetTimeSpan(dr.GetOrdinal(“Time7FieldName”));
How are you accessing the data? Using Entity Frameworks, StoredProcedures etc.
If you have to pass a string representation of the date make sure that you do it in the format "yyyy-mm-dd hh:mm:ss" otherwise you will run the risk of the dd/mm/yyyy vs mm/dd/yyyy confusion.
If you are using Entity Framework or DataSets then you should just pass the parameter a DataTime instance eg DateTime.Now
if your field is in time u can simply cast with (Timespan),
while (reader.Read())
{
TimeSpan DBStartTime = (TimeSpan)reader["StartTime"];
TimeSpan DBEndTime = (TimeSpan)reader["EndTime"];
}