Pregunta

After searching for a full day, I'm unable to find a solution, facing multiple conversion errors. Main objective is to convert a dd/MM/yyyy to yyyy-MM-dd "date" format to fit in SQL Server.

I have a SQL Server 2012 database with datatype date as a column in my table.

I'm using a jQuery datepicker with jquery-1.4.1-vsdoc.js on my project website that outputs dd/MM/yyyy which is obtained using

Dim dDate As DateTime = DateTime.Parse(Request.Form(txtStart.UniqueID))

Then I'm attempting to do an insert SQL using the date obtained but the database date format is yyyy-MM-dd.

Have tried this but it doesn't work:

SELECT CONVERT(date, CONVERT(DATETIME, '14/10/2011', 0), 120)

Tried this and it works but it's of varchar data type which is not what I need

SELECT REPLACE(CONVERT(VARCHAR(10), '15/4/2014', 111), '/', '-')  AS [YYYY-MM-DD]

I really need a code either on my website VB/C# code or SQL statement whichever to fulfill this please help

My script using the jQuery has already written in code the format that my sql is currently set, however at runtime it does not apply

<script type="text/javascript">
$(document).ready(function () {
    $("#<%=txtStart.ClientID %>").dynDateTime({
        showsTime: false,
        ifFormat: "%Y-%m-%d ",
        daFormat: "%l;%M %p, %e %m, %Y",
        align: "BR",
        electric: false,
        singleClick: false,
        displayArea: ".siblings('.dtcDisplayArea')",
        button: ".next()"
    });
});
</script>
¿Fue útil?

Solución

Main objective is to convert a dd/MM/yyyy to yyyy-MM-dd "date" format to fit in SQL

Don't! You should avoid string conversions as far as you possibly can. Keep your data in its natural representation for as much of the time as you can.

You may well need to parse the date from dd/MM/yyyy to DateTime to start with (although if you can avoid even this, do so - we don't know where your data comes from), but then you should leave it as a DateTime. Use parameterized SQL instead, passing the value of the parameter to the database as a DateTime. Of course, you should also make sure that the fields in your database are using the appropriate type to start with (not varchar). Ensuring that your schema matches your data is crucial to running a sane system.

The parsing part should be relatively simple. For example:

DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy",
                                    CultureInfo.InvariantCulture);

You may want to use a user's culture instead (depending on where the data has come from) and you may want to use DateTime.TryParseExact instead (if this is user-entered data rather than something from machine-to-machine communication).

Otros consejos

You have to remember that there is no format for DateTime.if you want convert some date string into DateTime and if you know the Date format upfront you can use DateTime.ParseExact()

Try This:

string strDate = "21/04/2014";
DateTime dt = DateTime.ParseExact(strDate,"dd/MM/yyyy",
                                                   CultureInfo.InvariantCulture);

now you can store the DateTime variable dt into database but if you want to display the DateTime in some format ex:yyyy-MM-dd you need to call ToString() as below

String datetime = dt.ToString("yyyy-MM-dd");

Use the dateFormat option

$(function(){
        $("#to").datepicker({ dateFormat: 'yy-mm-dd' });
        $("#from").datepicker({ dateFormat: 'yy-mm-dd' }).bind("change",function(){
            var minValue = $(this).val();
            minValue = $.datepicker.parseDate("yy-mm-dd", minValue);
            minValue.setDate(minValue.getDate()+1);
            $("#to").datepicker( "option", "minDate", minValue );
        })
    });

DEMO here

we can try ParseExact method while using InvariantCulture. This provides information about a specific culture. The information includes the names for the culture,the writing system( yyyy-MM-dd in your case) etc.

        String MyDateString;
        DateTime MyDateTime;

          MyDateString = txtDateOfIncidence.Text.Trim()+ " " + txtTiming.Text.Trim();
          MyDateTime = DateTime.ParseExact(MyDateString, "yyyy/MM/dd" + " hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top