Hi RichardSa,
Please refer below sample.
HTML
<form id="form1" runat="server">
<asp:TextBox ID="dateTimeTextBox" runat="server"></asp:TextBox>
<asp:Button ID="insertDateTimeButton" runat="server" Text="Insert DateTime" OnClientClick="insertDateTime()" />
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function insertDateTime() {
var dateTimeValue = $('[id*=dateTimeTextBox]').val();
var data = { dateTimeValue: dateTimeValue };
$.ajax({
url: "Default.aspx/InsertDateTimeMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.responseText);
}
});
}
</script>
Namespaces
C#
using System.Web.Services;
using System.Globalization;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Web.Services
Imports System.Globalization
Imports System.Configuration
Imports System.Data.SqlClient
Code
C#
[WebMethod]
public static string InsertDateTimeMethod(string dateTimeValue)
{
DateTime dateTime = new DateTime(2023, 03, 18, 14, 30, 0);
var data = new { dateTimeValue = dateTime.ToString("dd-MM-yyyy HH:mm:ss") };
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
string query = "INSERT INTO DateTimeTable (DateTimeValue) VALUES (@DateTimeValue)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@DateTimeValue", DateTime.ParseExact(dateTimeValue, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture));
con.Open();
cmd.ExecuteNonQuery();
}
return "DateTime value inserted successfully";
}
VB.Net
<WebMethod>
Public Shared Function InsertDateTimeMethod(ByVal dateTimeValue As String) As String
Dim dateTime As DateTime = New DateTime(2023, 3, 18, 14, 30, 0)
Dim data = New With {Key .dateTimeValue = dateTime.ToString("dd-MM-yyyy HH:mm:ss")}
Dim constring As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constring)
Dim query As String = "INSERT INTO DateTimeTable (DateTimeValue) VALUES (@DateTimeValue)"
Dim cmd As SqlCommand = New SqlCommand(query, con)
cmd.Parameters.AddWithValue("@DateTimeValue", DateTime.ParseExact(dateTimeValue, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture))
con.Open()
cmd.ExecuteNonQuery()
End Using
Return "DateTime value inserted successfully"
End Function
Screenshot