Failed to convert parameter value from a DateTimeOffset to a DateTime

Javier R 211 Reputation points
2021-03-10T10:25:35.197+00:00

Failed to convert parameter value from a DateTimeOffset to a DateTime . I have a datapicker where I choose the date with sql server to enter the date in the database that then in another window of the uwp app comes date.
76237-2021-03-10.png

Universal Windows Platform (UWP)
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,639 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Olaf Helper 40,656 Reputation points
    2021-03-10T10:39:45.547+00:00

    That exception "System.InvalidCastException" is raised by .NET, not by SQL Server.

    DatePicker.SelectedDate Property returns an object of type System.DateTimeOffset, which can not be implicit converted to date; you have to convert it first in .NET.

    0 comments No comments

  2. Dan Guzman 9,206 Reputation points
    2021-03-10T11:26:19.897+00:00

    Adding to @Olaf Helper answer, the SQL Server datetime type has no notion of an offset so you'll need to convert it to a datetime value of a specific timezone. If the client and server are in the same timezone, you could use DateNac.SelectedDate.Value.ToLocalTime(). For different timezones, standardize on storing values for a specific timezone to avoid ambiguity.. UTC is must commonly used (e.g. DateNac.SelectedDate.Value.ToUniversalTime()).

    Alternatively change the column type to datetimeoffset. This allows you to preserve the original value and compare naturally compare datetime values with different offsets in T-SQL.

    0 comments No comments

  3. AryaDing-MSFT 2,841 Reputation points
    2021-03-11T03:17:20.8+00:00

    Hi,

    Welcome to Microsoft Q&A!

    The reason for this issue is that the parameter type does not match the corresponding value type. Please check the following steps to do this.

    Change the code to:

    cmd.Parameters.Add("@duoDate",SqlDbType.DateTimeOffset).Value=DateNac.SelectedDate.Value;  
    

    In addition, you need to set the corresponding column type of sql server database to datetimeoffset.

    After my test, it is recommend to use SqlDbType.Date, which makes the time clearer, only the year, month and day, no minutes, seconds.
    For example:

    cmd.Parameters.Add("@duoDate", SqlDbType.Date).Value = DateNac.SelectedDate.Value.Date;  
    

    Note: set the corresponding column type of sql server database to date.


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  4. Javier R 211 Reputation points
    2021-03-18T21:13:37.827+00:00

    for the database for the datepicker that best option Date or datetime so that the date is saved in the database.