problem when comparing by date format


I retrieve a date from a record that is in the BD and it brings me in this format "07/01/2016 05:43:10 pm", then I compare that date to make a condition to update my record since it is the only field that can be different for all the other records of my BD, I can not modify the design of the table, I can only make use of the records, that date format is bringing me problems since the format of the date of my BD is "2016-01-07 17: 43: 11.790", so I tested my update from SQL Server and the "pm" is the problem you are not updating, how could you remove the "p.m.", and use

Dim fechaCompara = Convert.ToDateTime(Request.Form("txtFechaa"))

and still bringing "07/01/2016 05:43:10 p.m.", use VB.NET

asked by Ivxn 04.05.2016 в 17:06

2 answers


The problem may be in the regional configuration, but a somewhat generic solution is this:

Dim fechaCompara As DateTime = DateTime.Parse(DateTime.Parse(Request.Form("txtFechaa")).ToString("MM-dd-yyyy HH:mm:ss"))

Or, in the same way that you did:

Dim fechaCompara = DateTime.Parse(Convert.ToDateTime(Request.Form("txtFechaa")).ToString("MM-dd-yyyy HH:mm:ss"))

Where .ToString("MM-dd-yyyy HH:mm:ss") convert to string the date string you get at the beginning ( 07/01/2016 05:43:10 p.m. ) in 07-01-2016 17:43:10

To then convert 07-01-2016 17:43:10 in DateTime

When you call it, you have an object of type DateTime , with the regional configuration you need.

answered by 04.05.2016 / 17:24

The format you have in the db does not affect anything, but you should send a datetime as a parameter of the query that you execute

Dim fechaCompara As DateTime= Convert.ToDateTime(Request.Form("txtFechaa"))

Using conn As New SqlConnection("<connection string>")

    Dim query As String = "UPDATE NombreTabla SET fecha = @fecha WHERE campo = @id"
    Dim cmd As New SqlCommand(query, conn)
    cmd.Parameters.AddWithValue("@fecha", fechaCompara)
    cmd.Parameters.AddWithValue("@id", Convert.ToInt32(txtId.Text))

End Using

No matter the format of the date, whenever you use the parameter and assign a valid datetime

answered by 04.05.2016 в 17:32