Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. Error converting data type nvarchar to datetime, any suggestion

Error converting data type nvarchar to datetime, any suggestion

Scheduled Pinned Locked Moved C#
csharpdatabasehelp
27 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S suni_dotnet

    hi, cmd.CommandType = CommandType.StoredProcedure; string filldate = GridView2.Rows[e.RowIndex].Cells[2].Text; string freedate = GridView2.Rows[e.RowIndex].Cells[3].Text; cmd.Parameters.AddWithValue("@filleddate",filldate); cmd.Parameters.AddWithValue("@freedate", freedate); cmd.Parameters.AddWithValue("@nameofcustomer", GridView2.Rows[e.RowIndex].Cells[6].Text); try { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); } and stored procedure is: Insert into PresidentialSuite(DateWhenFilled,DateWhenFree,NameOfCustomer) values (@filleddate,@freedate,@nameofcustomer); SET @filleddate = Convert(datetime,@filleddate); SET @freedate = Convert(datetime,@freedate); Iam not converting any nvarchar to datetime. why iam getting this error. i tried number of ways of converting string to datetime in my C# code, but failed. so i used stored procedure. thanks in advance

    M Offline
    M Offline
    musefan
    wrote on last edited by
    #5

    what format is the original date in? and what format is the database storing dates? it should be fairly simple to convert to required date in c# not good to use stored procedure if original date and stored date formats are different cuz it cant handle the days and month being switched round i.e. dd/MM/yyyy and MM/dd/yyyy

    S 1 Reply Last reply
    0
    • M musefan

      what format is the original date in? and what format is the database storing dates? it should be fairly simple to convert to required date in c# not good to use stored procedure if original date and stored date formats are different cuz it cant handle the days and month being switched round i.e. dd/MM/yyyy and MM/dd/yyyy

      S Offline
      S Offline
      suni_dotnet
      wrote on last edited by
      #6

      i need to input values through gridview (cell),into db(sqlserver, datatype is datetime) i didnot specify any format, my code takes the text values and converts to datetime(stored procedure) and stores. i tried: Convert.ToDatetime DateTime.Parse using IFormatterProvider--Globilization...

      M 1 Reply Last reply
      0
      • S suni_dotnet

        i need to input values through gridview (cell),into db(sqlserver, datatype is datetime) i didnot specify any format, my code takes the text values and converts to datetime(stored procedure) and stores. i tried: Convert.ToDatetime DateTime.Parse using IFormatterProvider--Globilization...

        M Offline
        M Offline
        musefan
        wrote on last edited by
        #7

        where does the nvarchar come into it then? are you passing the datetime value into the database via an sql statement? if the error is that the database is receiving an nvarchar when it wants a datetime, you may have a issue with your sql statement. Datetime needs to be inclosed with the hash symbols (I Think) i.e. #01/01/2000#

        S 1 Reply Last reply
        0
        • N Not Active

          suni_dotnet wrote:

          i tried number of ways of converting string to datetime in my C# code, but failed.

          You tried DateTime.Parse(...) and it failed? :confused: Obviously the input needs to be validated before even getting to your database.


          only two letters away from being an asset

          S Offline
          S Offline
          suni_dotnet
          wrote on last edited by
          #8

          hi, how can i validate. can use DateTime.TryParse(); ?

          N 1 Reply Last reply
          0
          • S suni_dotnet

            hi, cmd.CommandType = CommandType.StoredProcedure; string filldate = GridView2.Rows[e.RowIndex].Cells[2].Text; string freedate = GridView2.Rows[e.RowIndex].Cells[3].Text; cmd.Parameters.AddWithValue("@filleddate",filldate); cmd.Parameters.AddWithValue("@freedate", freedate); cmd.Parameters.AddWithValue("@nameofcustomer", GridView2.Rows[e.RowIndex].Cells[6].Text); try { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); } and stored procedure is: Insert into PresidentialSuite(DateWhenFilled,DateWhenFree,NameOfCustomer) values (@filleddate,@freedate,@nameofcustomer); SET @filleddate = Convert(datetime,@filleddate); SET @freedate = Convert(datetime,@freedate); Iam not converting any nvarchar to datetime. why iam getting this error. i tried number of ways of converting string to datetime in my C# code, but failed. so i used stored procedure. thanks in advance

            J Offline
            J Offline
            Jon Rista
            wrote on last edited by
            #9

            Don't convert in the database. You should convert in C# first, because .NET handles times in a completely different way than SQL Server. SQL Server requires times input as strings to follow a specific format. If you convert in C# first, ADO.NET will take care of the rest:

            string freedateraw = Gridview2.Rows[e.RowIndex].Cells[3].Text;
            DateTime? freedate = (freedateraw == null ? (DateTime?)null : Convert.ToDateTime(freedateraw));

            cmd.Parameters.AddWithValue("@freedate", freedate);

            N S 2 Replies Last reply
            0
            • S suni_dotnet

              hi, how can i validate. can use DateTime.TryParse(); ?

              N Offline
              N Offline
              Not Active
              wrote on last edited by
              #10

              suni_dotnet wrote:

              how can i validate.

              :rolleyes: Maybe something like a validation control, regex, using a DateTime picker, using your brain would be the first step.


              only two letters away from being an asset

              S 1 Reply Last reply
              0
              • M musefan

                where does the nvarchar come into it then? are you passing the datetime value into the database via an sql statement? if the error is that the database is receiving an nvarchar when it wants a datetime, you may have a issue with your sql statement. Datetime needs to be inclosed with the hash symbols (I Think) i.e. #01/01/2000#

                S Offline
                S Offline
                suni_dotnet
                wrote on last edited by
                #11

                hi, i tried with #date#, its not working. my stored procedure(present in my main question)i didnot use any nvarchar. i declared variables as datetime. i used IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-US", true); DateTime theDateTime = DateTime.ParseExact(filldate, "mm/dd/yyyy HH:mm:ss", theCultureInfo); i entered the value in same format in cell. i got the error: String was not recognized as a valid DateTime.

                1 Reply Last reply
                0
                • J Jon Rista

                  Don't convert in the database. You should convert in C# first, because .NET handles times in a completely different way than SQL Server. SQL Server requires times input as strings to follow a specific format. If you convert in C# first, ADO.NET will take care of the rest:

                  string freedateraw = Gridview2.Rows[e.RowIndex].Cells[3].Text;
                  DateTime? freedate = (freedateraw == null ? (DateTime?)null : Convert.ToDateTime(freedateraw));

                  cmd.Parameters.AddWithValue("@freedate", freedate);

                  N Offline
                  N Offline
                  Not Active
                  wrote on last edited by
                  #12

                  What if freedateraw is an empty string? freedateraw == null won't work and Convert.ToDateTime(freedateraw) throw an exception. If freedateraw is not null or empty the convert may still throw an exception if it isn't in a valid format. There is no point to this cast;(DateTime?)null


                  only two letters away from being an asset

                  J 1 Reply Last reply
                  0
                  • N Not Active

                    suni_dotnet wrote:

                    how can i validate.

                    :rolleyes: Maybe something like a validation control, regex, using a DateTime picker, using your brain would be the first step.


                    only two letters away from being an asset

                    S Offline
                    S Offline
                    suni_dotnet
                    wrote on last edited by
                    #13

                    hi i tried alot before posting this question. searched google (1 week)... but couldnot find any solution.. i used my brain by all means but couldnot find solution. iam a learner so does everyone. if everyone knows everything.. there wont be anything... iam here to learn... if possible plz guide me rather than ..

                    N 1 Reply Last reply
                    0
                    • J Jon Rista

                      Don't convert in the database. You should convert in C# first, because .NET handles times in a completely different way than SQL Server. SQL Server requires times input as strings to follow a specific format. If you convert in C# first, ADO.NET will take care of the rest:

                      string freedateraw = Gridview2.Rows[e.RowIndex].Cells[3].Text;
                      DateTime? freedate = (freedateraw == null ? (DateTime?)null : Convert.ToDateTime(freedateraw));

                      cmd.Parameters.AddWithValue("@freedate", freedate);

                      S Offline
                      S Offline
                      suni_dotnet
                      wrote on last edited by
                      #14

                      i tried i got error, string not recognised as valid datetime. i used many formatings "mm/dd/yyyy",... same error

                      J 1 Reply Last reply
                      0
                      • S suni_dotnet

                        hi i tried alot before posting this question. searched google (1 week)... but couldnot find any solution.. i used my brain by all means but couldnot find solution. iam a learner so does everyone. if everyone knows everything.. there wont be anything... iam here to learn... if possible plz guide me rather than ..

                        N Offline
                        N Offline
                        Not Active
                        wrote on last edited by
                        #15

                        In your weeks worth of searching you didn't come across anything like this :omg: :rolleyes: http://msdn.microsoft.com/en-us/library/7kh55542.aspx[^][^]


                        only two letters away from being an asset

                        S 1 Reply Last reply
                        0
                        • N Not Active

                          In your weeks worth of searching you didn't come across anything like this :omg: :rolleyes: http://msdn.microsoft.com/en-us/library/7kh55542.aspx[^][^]


                          only two letters away from being an asset

                          S Offline
                          S Offline
                          suni_dotnet
                          wrote on last edited by
                          #16

                          that i know, its getting into argument.. can u help me with little coding. else no problem. thank you

                          N 1 Reply Last reply
                          0
                          • S suni_dotnet

                            that i know, its getting into argument.. can u help me with little coding. else no problem. thank you

                            N Offline
                            N Offline
                            Not Active
                            wrote on last edited by
                            #17

                            What help do you need?!? You have had multiple answers, its time for you to apply it.


                            only two letters away from being an asset

                            1 Reply Last reply
                            0
                            • N Not Active

                              What if freedateraw is an empty string? freedateraw == null won't work and Convert.ToDateTime(freedateraw) throw an exception. If freedateraw is not null or empty the convert may still throw an exception if it isn't in a valid format. There is no point to this cast;(DateTime?)null


                              only two letters away from being an asset

                              J Offline
                              J Offline
                              Jon Rista
                              wrote on last edited by
                              #18

                              Actually, there absolutely is a point to the cast. Test it for yourself: string raw = null; DateTime? dt = (String.IsNullOrEmpty(raw) ? null : Convert.ToDateTime(raw)); You will get the following compilation error: Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime' Yes, you are correct, checking for null is not sufficient, checking String.IsNullOrEmpty() is correct. That wasn't the real point of my response, though. But check that ternary statement...there absolutely is a point to that cast, its reqired to compile.

                              N 1 Reply Last reply
                              0
                              • S suni_dotnet

                                i tried i got error, string not recognised as valid datetime. i used many formatings "mm/dd/yyyy",... same error

                                J Offline
                                J Offline
                                Jon Rista
                                wrote on last edited by
                                #19

                                You need to change your stored proc, too. If your stored proc is like this: CREATE PROCEDURE SomeProc ( @filldate varchar(10), @freedate varchar(10), @name varchar(50) ) Then you need to change that to: CREATE PROCEDURE SomeProc ( @filldate datetime, @freedate datetime, @name varchar(50) ) And get rid of your conversion in the stored proc. You can't convert in both places...either convert in C#, or convert in the stored proc. If you convert in the stored proc, you will have to manually reformat the freedate and filldate strings to conform to the datetime format required by SQL Server to pass them in and convert them in the proc. Converting to DateTime in C# will be simpler, and a more stable implementation, than reformatting and converting in the proc.

                                S 1 Reply Last reply
                                0
                                • J Jon Rista

                                  You need to change your stored proc, too. If your stored proc is like this: CREATE PROCEDURE SomeProc ( @filldate varchar(10), @freedate varchar(10), @name varchar(50) ) Then you need to change that to: CREATE PROCEDURE SomeProc ( @filldate datetime, @freedate datetime, @name varchar(50) ) And get rid of your conversion in the stored proc. You can't convert in both places...either convert in C#, or convert in the stored proc. If you convert in the stored proc, you will have to manually reformat the freedate and filldate strings to conform to the datetime format required by SQL Server to pass them in and convert them in the proc. Converting to DateTime in C# will be simpler, and a more stable implementation, than reformatting and converting in the proc.

                                  S Offline
                                  S Offline
                                  suni_dotnet
                                  wrote on last edited by
                                  #20

                                  hi, i declared as datetime in stored procedure. yeah iam trying in C#. ALTER PROCEDURE InsertSuite @filleddate datetime, @freedate datetime, @nameofcustomer varchar(50) AS BEGIN SET NOCOUNT ON Insert into PresidentialSuite(DateWhenFilled,DateWhenFree,NameOfCustomer) values (@filleddate,@freedate,@nameofcustomer); END dont know why iam getting such error. thanks

                                  J 1 Reply Last reply
                                  0
                                  • J Jon Rista

                                    Actually, there absolutely is a point to the cast. Test it for yourself: string raw = null; DateTime? dt = (String.IsNullOrEmpty(raw) ? null : Convert.ToDateTime(raw)); You will get the following compilation error: Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime' Yes, you are correct, checking for null is not sufficient, checking String.IsNullOrEmpty() is correct. That wasn't the real point of my response, though. But check that ternary statement...there absolutely is a point to that cast, its reqired to compile.

                                    N Offline
                                    N Offline
                                    Not Active
                                    wrote on last edited by
                                    #21

                                    Your correct, I forgot the IDE wasn't smart enough to figure out its a nullable type and can be null


                                    only two letters away from being an asset

                                    J 1 Reply Last reply
                                    0
                                    • S suni_dotnet

                                      hi, i declared as datetime in stored procedure. yeah iam trying in C#. ALTER PROCEDURE InsertSuite @filleddate datetime, @freedate datetime, @nameofcustomer varchar(50) AS BEGIN SET NOCOUNT ON Insert into PresidentialSuite(DateWhenFilled,DateWhenFree,NameOfCustomer) values (@filleddate,@freedate,@nameofcustomer); END dont know why iam getting such error. thanks

                                      J Offline
                                      J Offline
                                      Jon Rista
                                      wrote on last edited by
                                      #22

                                      What is the error you are currently getting?

                                      S 1 Reply Last reply
                                      0
                                      • N Not Active

                                        Your correct, I forgot the IDE wasn't smart enough to figure out its a nullable type and can be null


                                        only two letters away from being an asset

                                        J Offline
                                        J Offline
                                        Jon Rista
                                        wrote on last edited by
                                        #23

                                        You would think the C# compiler would be intelligent enough to handle that. Maybe the co/contravariance stuff in C# 4.0 will simplify such scenarios...

                                        1 Reply Last reply
                                        0
                                        • J Jon Rista

                                          What is the error you are currently getting?

                                          S Offline
                                          S Offline
                                          suni_dotnet
                                          wrote on last edited by
                                          #24

                                          "String was not recognized as a valid DateTime." though whatever conversions i used and formats iam getting same error.

                                          J 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups