3

I'm getting date from java script and want to store in sql table by executing c# code.

How to do?

java script format: Mon Oct 15 15:34:18 UTC+0530 2012

mssql format: 2012-10-15 16:18:04.000

balaji
  • 1,236
  • 2
  • 18
  • 28
  • how about storing it as a timestamp (long)? And then converting and rendering as needed by the UI. – techfoobar Oct 15 '12 at 12:02
  • do you think you are the first person on this planet solving this problem? :) have you tried searching? see [Javascript date to C# via Ajax](http://stackoverflow.com/q/1877788/944681) or [Parsing Date-and-Times from JavaScript to C#](http://stackoverflow.com/q/10872143/944681) – Michal Klouda Oct 15 '12 at 12:03
  • yes. i tried but not able to do – balaji Oct 15 '12 at 12:05

1 Answers1

5

You may parse the JavaScript date to C# DateTime type (using DateTime.ParseExact) and then save it in SQL server using Parameterized query. For your date format you can try:

string str = "Mon Oct 15 15:34:18 UTC+0530 2012"; //your javascript date as string
DateTime dt = DateTime.ParseExact(str, 
                                  "ddd MMM d HH:mm:ss UTCzzzzz yyyy", 
                                   CultureInfo.InvariantCulture);
Habib
  • 219,104
  • 29
  • 407
  • 436
  • this is my code Dim time As String = DateTime.ParseExact(hdnTime.Value, "ddd MMM d HH:mm:ss UTCzzzzz yyyy", InvariantCulture) but not able to store..its throwing error – balaji Oct 15 '12 at 12:08
  • @balaji, my answer is in C# , I have just divided the DateTime.Parse call to multiple lines for readability – Habib Oct 15 '12 at 12:11
  • my run time query INSERT INTO payu_transactions(txn_id,txn_customerid,txn_amount,txn_datetime)VALUES('345785','30','656','15/10/2012 17:41:59') – balaji Oct 15 '12 at 12:12
  • getting this error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value." – balaji Oct 15 '12 at 12:14
  • What is the data type of your Date column in Database ? is it `varchar` ? – Habib Oct 15 '12 at 12:16
  • I believe you are not using Parameterized query, Its better if you see: [Parametrized query](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx) – Habib Oct 15 '12 at 12:23
  • 1
    @balaji don't concatenate the values; just pass the value down as a parameter. If you **ever** need to know what the date-format is on a database server, then you're doing it wrong™. Your SQL should look like `.... values(@id, @name, @date, ...)` – Marc Gravell Oct 15 '12 at 12:26