How to properly format Date in yyyy-mm-dd?How to use ThreeTenABP in Android ProjectHow to return only the Date from a SQL Server DateTime datatypeHow do you get a timestamp in JavaScript?How do I read / convert an InputStream into a String in Java?Compare two dates with JavaScriptWhere can I find documentation on formatting a date in JavaScript?Detecting an “invalid date” Date instance in JavaScriptYYYY-MM-DD format date in shell scriptHow to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?How do I get the current date in JavaScript?How to format a JavaScript date

Does throwing a penny at a train stop the train?

Managing and organizing the massively increased number of classes after switching to SOLID?

Was the Ford Model T black because of the speed black paint dries?

Why does the U.S. tolerate foreign influence from Saudi Arabia and Israel on its domestic policies while not tolerating that from China or Russia?

How might the United Kingdom become a republic?

I received a dinner invitation through my employer's email. Is it OK to attend?

What would be the ideal melee weapon made of "Phase Metal"?

When did the Roman Empire fall according to contemporaries?

Can I call 112 to check a police officer's identity in the Czech Republic?

Did Lincoln tell Stowe "So you're the little woman that started this great war!"?

Can I play a first turn Simic Growth Chamber to have 3 mana available in the second turn?

Why are they 'nude photos'?

Are unclear "take-it or leave-it" contracts interpreted in my favor?

How is angular momentum conserved for the orbiting body if the centripetal force disappears?

Is lack of functional requirements agile?

Novel where a group of scientists in a spaceship encounter various aliens

references on the empirical study on the practice of OR

Is there a word for a message that is intended to be intercepted by an adversary?

Robbers: The Hidden OEIS Substring

Do you know your 'KVZ's?

<schwitz>, <zwinker> etc. Does German always use 2nd Person Singular Imperative verbs for emoticons? If so, why?

Is purchasing foreign currency before going abroad a losing proposition?

Setting MAC field to all-zero to indicate unencrypted data

Graduate student with abysmal English writing skills, how to help



How to properly format Date in yyyy-mm-dd?


How to use ThreeTenABP in Android ProjectHow to return only the Date from a SQL Server DateTime datatypeHow do you get a timestamp in JavaScript?How do I read / convert an InputStream into a String in Java?Compare two dates with JavaScriptWhere can I find documentation on formatting a date in JavaScript?Detecting an “invalid date” Date instance in JavaScriptYYYY-MM-DD format date in shell scriptHow to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?How do I get the current date in JavaScript?How to format a JavaScript date






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








-1















I have a column in my table of Date type in MYSQL and inserting the date format of 25-March-2019 hh:mm:ss returns an error telling me incorrect data value.



So I have my code written like this:



 String startdt=request.getParameter("startdate");
String enddate=request.getParameter("enddate");
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date Startdate=dateFormat.parse(startdt);
Date Enddate=dateFormat.parse(enddate);


And I am passing Startdate and Enddate to a function that inserts into my table column.



Is there a way I can have Startdate and Enddate above just return in yyyy-mm-dd without the time so I can insert to my db without error?










share|improve this question



















  • 3





    Why are you using string formatting at all instead of using a Date or Instant object directly?

    – chrylis
    Mar 26 at 3:28






  • 1





    You really need to show how you're handling the SQL. This smells like you have injection attacks. (Additionally, while it may be unavoidable in your specific case if you're manually parsing parameters from an HttpServletRequest you're Doing It Wrong™, as all major frameworks will do this for you.)

    – chrylis
    Mar 26 at 3:31







  • 1





    I recommend you don’t use SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use LocalDate from java.time, the modern Java date and time API. You may not need an explicit formatter. And you certainly don’t need to format your LocalDate before handing it over to MySQL.

    – Ole V.V.
    Mar 26 at 8:08






  • 1





    @OleV.V. Yea LocalDate is probably the latest library that most people would suggest but unfortunately,it only works for Java 8 and above.

    – Daredevil
    Mar 26 at 8:10






  • 1





    @Daredevil You should have disclosed any constraints, such as being limited to Java 7, in your Question.

    – Basil Bourque
    Mar 26 at 16:30

















-1















I have a column in my table of Date type in MYSQL and inserting the date format of 25-March-2019 hh:mm:ss returns an error telling me incorrect data value.



So I have my code written like this:



 String startdt=request.getParameter("startdate");
String enddate=request.getParameter("enddate");
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date Startdate=dateFormat.parse(startdt);
Date Enddate=dateFormat.parse(enddate);


And I am passing Startdate and Enddate to a function that inserts into my table column.



Is there a way I can have Startdate and Enddate above just return in yyyy-mm-dd without the time so I can insert to my db without error?










share|improve this question



















  • 3





    Why are you using string formatting at all instead of using a Date or Instant object directly?

    – chrylis
    Mar 26 at 3:28






  • 1





    You really need to show how you're handling the SQL. This smells like you have injection attacks. (Additionally, while it may be unavoidable in your specific case if you're manually parsing parameters from an HttpServletRequest you're Doing It Wrong™, as all major frameworks will do this for you.)

    – chrylis
    Mar 26 at 3:31







  • 1





    I recommend you don’t use SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use LocalDate from java.time, the modern Java date and time API. You may not need an explicit formatter. And you certainly don’t need to format your LocalDate before handing it over to MySQL.

    – Ole V.V.
    Mar 26 at 8:08






  • 1





    @OleV.V. Yea LocalDate is probably the latest library that most people would suggest but unfortunately,it only works for Java 8 and above.

    – Daredevil
    Mar 26 at 8:10






  • 1





    @Daredevil You should have disclosed any constraints, such as being limited to Java 7, in your Question.

    – Basil Bourque
    Mar 26 at 16:30













-1












-1








-1








I have a column in my table of Date type in MYSQL and inserting the date format of 25-March-2019 hh:mm:ss returns an error telling me incorrect data value.



So I have my code written like this:



 String startdt=request.getParameter("startdate");
String enddate=request.getParameter("enddate");
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date Startdate=dateFormat.parse(startdt);
Date Enddate=dateFormat.parse(enddate);


And I am passing Startdate and Enddate to a function that inserts into my table column.



Is there a way I can have Startdate and Enddate above just return in yyyy-mm-dd without the time so I can insert to my db without error?










share|improve this question
















I have a column in my table of Date type in MYSQL and inserting the date format of 25-March-2019 hh:mm:ss returns an error telling me incorrect data value.



So I have my code written like this:



 String startdt=request.getParameter("startdate");
String enddate=request.getParameter("enddate");
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date Startdate=dateFormat.parse(startdt);
Date Enddate=dateFormat.parse(enddate);


And I am passing Startdate and Enddate to a function that inserts into my table column.



Is there a way I can have Startdate and Enddate above just return in yyyy-mm-dd without the time so I can insert to my db without error?







java date java-7






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 22 at 21:54









halfer

15.1k7 gold badges60 silver badges124 bronze badges




15.1k7 gold badges60 silver badges124 bronze badges










asked Mar 26 at 3:27









DaredevilDaredevil

53414 bronze badges




53414 bronze badges







  • 3





    Why are you using string formatting at all instead of using a Date or Instant object directly?

    – chrylis
    Mar 26 at 3:28






  • 1





    You really need to show how you're handling the SQL. This smells like you have injection attacks. (Additionally, while it may be unavoidable in your specific case if you're manually parsing parameters from an HttpServletRequest you're Doing It Wrong™, as all major frameworks will do this for you.)

    – chrylis
    Mar 26 at 3:31







  • 1





    I recommend you don’t use SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use LocalDate from java.time, the modern Java date and time API. You may not need an explicit formatter. And you certainly don’t need to format your LocalDate before handing it over to MySQL.

    – Ole V.V.
    Mar 26 at 8:08






  • 1





    @OleV.V. Yea LocalDate is probably the latest library that most people would suggest but unfortunately,it only works for Java 8 and above.

    – Daredevil
    Mar 26 at 8:10






  • 1





    @Daredevil You should have disclosed any constraints, such as being limited to Java 7, in your Question.

    – Basil Bourque
    Mar 26 at 16:30












  • 3





    Why are you using string formatting at all instead of using a Date or Instant object directly?

    – chrylis
    Mar 26 at 3:28






  • 1





    You really need to show how you're handling the SQL. This smells like you have injection attacks. (Additionally, while it may be unavoidable in your specific case if you're manually parsing parameters from an HttpServletRequest you're Doing It Wrong™, as all major frameworks will do this for you.)

    – chrylis
    Mar 26 at 3:31







  • 1





    I recommend you don’t use SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use LocalDate from java.time, the modern Java date and time API. You may not need an explicit formatter. And you certainly don’t need to format your LocalDate before handing it over to MySQL.

    – Ole V.V.
    Mar 26 at 8:08






  • 1





    @OleV.V. Yea LocalDate is probably the latest library that most people would suggest but unfortunately,it only works for Java 8 and above.

    – Daredevil
    Mar 26 at 8:10






  • 1





    @Daredevil You should have disclosed any constraints, such as being limited to Java 7, in your Question.

    – Basil Bourque
    Mar 26 at 16:30







3




3





Why are you using string formatting at all instead of using a Date or Instant object directly?

– chrylis
Mar 26 at 3:28





Why are you using string formatting at all instead of using a Date or Instant object directly?

– chrylis
Mar 26 at 3:28




1




1





You really need to show how you're handling the SQL. This smells like you have injection attacks. (Additionally, while it may be unavoidable in your specific case if you're manually parsing parameters from an HttpServletRequest you're Doing It Wrong™, as all major frameworks will do this for you.)

– chrylis
Mar 26 at 3:31






You really need to show how you're handling the SQL. This smells like you have injection attacks. (Additionally, while it may be unavoidable in your specific case if you're manually parsing parameters from an HttpServletRequest you're Doing It Wrong™, as all major frameworks will do this for you.)

– chrylis
Mar 26 at 3:31





1




1





I recommend you don’t use SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use LocalDate from java.time, the modern Java date and time API. You may not need an explicit formatter. And you certainly don’t need to format your LocalDate before handing it over to MySQL.

– Ole V.V.
Mar 26 at 8:08





I recommend you don’t use SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use LocalDate from java.time, the modern Java date and time API. You may not need an explicit formatter. And you certainly don’t need to format your LocalDate before handing it over to MySQL.

– Ole V.V.
Mar 26 at 8:08




1




1





@OleV.V. Yea LocalDate is probably the latest library that most people would suggest but unfortunately,it only works for Java 8 and above.

– Daredevil
Mar 26 at 8:10





@OleV.V. Yea LocalDate is probably the latest library that most people would suggest but unfortunately,it only works for Java 8 and above.

– Daredevil
Mar 26 at 8:10




1




1





@Daredevil You should have disclosed any constraints, such as being limited to Java 7, in your Question.

– Basil Bourque
Mar 26 at 16:30





@Daredevil You should have disclosed any constraints, such as being limited to Java 7, in your Question.

– Basil Bourque
Mar 26 at 16:30












2 Answers
2






active

oldest

votes


















3














tl;dr



myPreparedStatement
.setObject(
LocalDate.parse( "2019-01-23" )
) ;



DATE in MySQL is date-only



The DATE type in MySQL is a date-only value, without time-of-day and without time zone.



Excerpting from MySQL 8.0 documentation:




The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.




Use a date-only type in Java for data coming from a date-only type in your database. The java.util.Date class you are trying to use is not a date, it is a moment in UTC, a date with time-of-day and offset-from-UTC of zero, all tracked as a count of milliseconds from the first moment of 1970 in UTC. The misnaming of that class is only the first of many poor design choices made by those programmers. Move on to java.time classes instead. Stop using Date.




MM = month number, not name



Your format of "yyyy-MM-dd" is for a numeric month, not the string of month name shown in your example value of 25-March-2019.



Avoid legacy date-time classes



The SimpleDateFormat and Date classes are terrible, a wretched mess of bad design. They were supplanted years ago with the adoption of JSR 310, implemented in the java.time classes.



Smart objects, not dumb strings



Exchange objects with your database where possible, not text.



As of JDBC 4.2, we can directly exchanged java.time objects with the database. For a date-only value, as with SQL-standard DATE type, use the java.time.LocalDate class.



Apparently, your text inputs for date values is YYYY-MM-DD which is standard ISO 8601 format. The java.time classes use ISO 8601 formats by default. So no need to specify a formatting pattern.



LocalDate localDate = LocalDate.parse( "2019-01-23" ) ;
myPreparedStatement.setObject( … , localDate ) ;


Retrieval.



LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;



localDate.toString(): 2019-01-23




If you want to produce a string representing the value of that LocalDate object in a different textual format, use the DateTimeFormatter class. Search Stack Overflow for more info as it, like the rest of your Question, has been covered many times already on Stack Overflow. Do search Stack Overflow before posting.



Tip: Generally best to use a PreparedStatement in your JDBC work. One major benefit is thwarting SQL Injection security attacks.




About java.time



The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.



To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.



The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.



You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



Where to obtain the java.time classes?




  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

    • Java 9 adds some minor features and fixes.



  • Java SE 6 and Java SE 7

    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.



  • Android

    • Later versions of Android bundle implementations of the java.time classes.

    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.






share|improve this answer
































    2














    Java 7 and ThreeTen Backport



     DateTimeFormatter formatter
    = DateTimeFormatter.ofPattern("d-MMMM-uuuu HH:mm:ss", Locale.ENGLISH);
    String dateFromHtmlForm = "25-March-2019 22:43:55";
    LocalDateTime dateTime = LocalDateTime.parse(dateFromHtmlForm, formatter);
    // We are discarding the time of day and only saving the date
    java.sql.Date dateToSave = DateTimeUtils.toSqlDate(dateTime.toLocalDate());

    String insertSql = "insert into your_table (your_date_column) values (?);";
    try (PreparedStatement insertStatement
    = yourDatabaseConnection.prepareStatement(insertSql))
    insertStatement.setDate(1, dateToSave);
    int rowsInserted = insertStatement.executeUpdate();



    As has already been said, pass date objects to MySQL, not strings. In Java 8 and later these would have been LocalDate objects, but in Java 7 we will need to make do with the poorly designed java.sql.Date class. It’s still better than strings. And the conversion from LocalDate is straightforward.



    On Java 7 we can use java.time through the backport, ThreeTen Backport (ThreeTen for JSR-310). My imports are:



    import org.threeten.bp.DateTimeUtils;
    import org.threeten.bp.LocalDateTime;
    import org.threeten.bp.format.DateTimeFormatter;


    Why would we want to use an external library for this? There are pros and cons, of course. Advantages include:



    • java.time is so much nicer to work with than the old-fashoined Date and SimpleDateFormat and gives clearer code.

    • It’s future-proof: once you move to Java 8 or later, all you need to do is change your import statements (and discard the library and retest).

    Links




    • Oracle tutorial: Date Time explaining how to use java.time.


    • Java Specification Request (JSR) 310, where java.time was first described.


    • ThreeTen Backport project, the backport of java.time to Java 6 and 7.


    • ThreeTenABP, Android edition of ThreeTen Backport


    • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.





    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55349434%2fhow-to-properly-format-date-in-yyyy-mm-dd%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      tl;dr



      myPreparedStatement
      .setObject(
      LocalDate.parse( "2019-01-23" )
      ) ;



      DATE in MySQL is date-only



      The DATE type in MySQL is a date-only value, without time-of-day and without time zone.



      Excerpting from MySQL 8.0 documentation:




      The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.




      Use a date-only type in Java for data coming from a date-only type in your database. The java.util.Date class you are trying to use is not a date, it is a moment in UTC, a date with time-of-day and offset-from-UTC of zero, all tracked as a count of milliseconds from the first moment of 1970 in UTC. The misnaming of that class is only the first of many poor design choices made by those programmers. Move on to java.time classes instead. Stop using Date.




      MM = month number, not name



      Your format of "yyyy-MM-dd" is for a numeric month, not the string of month name shown in your example value of 25-March-2019.



      Avoid legacy date-time classes



      The SimpleDateFormat and Date classes are terrible, a wretched mess of bad design. They were supplanted years ago with the adoption of JSR 310, implemented in the java.time classes.



      Smart objects, not dumb strings



      Exchange objects with your database where possible, not text.



      As of JDBC 4.2, we can directly exchanged java.time objects with the database. For a date-only value, as with SQL-standard DATE type, use the java.time.LocalDate class.



      Apparently, your text inputs for date values is YYYY-MM-DD which is standard ISO 8601 format. The java.time classes use ISO 8601 formats by default. So no need to specify a formatting pattern.



      LocalDate localDate = LocalDate.parse( "2019-01-23" ) ;
      myPreparedStatement.setObject( … , localDate ) ;


      Retrieval.



      LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;



      localDate.toString(): 2019-01-23




      If you want to produce a string representing the value of that LocalDate object in a different textual format, use the DateTimeFormatter class. Search Stack Overflow for more info as it, like the rest of your Question, has been covered many times already on Stack Overflow. Do search Stack Overflow before posting.



      Tip: Generally best to use a PreparedStatement in your JDBC work. One major benefit is thwarting SQL Injection security attacks.




      About java.time



      The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.



      To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.



      The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.



      You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



      Where to obtain the java.time classes?




      • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

        • Java 9 adds some minor features and fixes.



      • Java SE 6 and Java SE 7

        • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.



      • Android

        • Later versions of Android bundle implementations of the java.time classes.

        • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


      The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.






      share|improve this answer





























        3














        tl;dr



        myPreparedStatement
        .setObject(
        LocalDate.parse( "2019-01-23" )
        ) ;



        DATE in MySQL is date-only



        The DATE type in MySQL is a date-only value, without time-of-day and without time zone.



        Excerpting from MySQL 8.0 documentation:




        The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.




        Use a date-only type in Java for data coming from a date-only type in your database. The java.util.Date class you are trying to use is not a date, it is a moment in UTC, a date with time-of-day and offset-from-UTC of zero, all tracked as a count of milliseconds from the first moment of 1970 in UTC. The misnaming of that class is only the first of many poor design choices made by those programmers. Move on to java.time classes instead. Stop using Date.




        MM = month number, not name



        Your format of "yyyy-MM-dd" is for a numeric month, not the string of month name shown in your example value of 25-March-2019.



        Avoid legacy date-time classes



        The SimpleDateFormat and Date classes are terrible, a wretched mess of bad design. They were supplanted years ago with the adoption of JSR 310, implemented in the java.time classes.



        Smart objects, not dumb strings



        Exchange objects with your database where possible, not text.



        As of JDBC 4.2, we can directly exchanged java.time objects with the database. For a date-only value, as with SQL-standard DATE type, use the java.time.LocalDate class.



        Apparently, your text inputs for date values is YYYY-MM-DD which is standard ISO 8601 format. The java.time classes use ISO 8601 formats by default. So no need to specify a formatting pattern.



        LocalDate localDate = LocalDate.parse( "2019-01-23" ) ;
        myPreparedStatement.setObject( … , localDate ) ;


        Retrieval.



        LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;



        localDate.toString(): 2019-01-23




        If you want to produce a string representing the value of that LocalDate object in a different textual format, use the DateTimeFormatter class. Search Stack Overflow for more info as it, like the rest of your Question, has been covered many times already on Stack Overflow. Do search Stack Overflow before posting.



        Tip: Generally best to use a PreparedStatement in your JDBC work. One major benefit is thwarting SQL Injection security attacks.




        About java.time



        The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.



        To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.



        The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.



        You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



        Where to obtain the java.time classes?




        • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

          • Java 9 adds some minor features and fixes.



        • Java SE 6 and Java SE 7

          • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.



        • Android

          • Later versions of Android bundle implementations of the java.time classes.

          • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


        The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.






        share|improve this answer



























          3












          3








          3







          tl;dr



          myPreparedStatement
          .setObject(
          LocalDate.parse( "2019-01-23" )
          ) ;



          DATE in MySQL is date-only



          The DATE type in MySQL is a date-only value, without time-of-day and without time zone.



          Excerpting from MySQL 8.0 documentation:




          The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.




          Use a date-only type in Java for data coming from a date-only type in your database. The java.util.Date class you are trying to use is not a date, it is a moment in UTC, a date with time-of-day and offset-from-UTC of zero, all tracked as a count of milliseconds from the first moment of 1970 in UTC. The misnaming of that class is only the first of many poor design choices made by those programmers. Move on to java.time classes instead. Stop using Date.




          MM = month number, not name



          Your format of "yyyy-MM-dd" is for a numeric month, not the string of month name shown in your example value of 25-March-2019.



          Avoid legacy date-time classes



          The SimpleDateFormat and Date classes are terrible, a wretched mess of bad design. They were supplanted years ago with the adoption of JSR 310, implemented in the java.time classes.



          Smart objects, not dumb strings



          Exchange objects with your database where possible, not text.



          As of JDBC 4.2, we can directly exchanged java.time objects with the database. For a date-only value, as with SQL-standard DATE type, use the java.time.LocalDate class.



          Apparently, your text inputs for date values is YYYY-MM-DD which is standard ISO 8601 format. The java.time classes use ISO 8601 formats by default. So no need to specify a formatting pattern.



          LocalDate localDate = LocalDate.parse( "2019-01-23" ) ;
          myPreparedStatement.setObject( … , localDate ) ;


          Retrieval.



          LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;



          localDate.toString(): 2019-01-23




          If you want to produce a string representing the value of that LocalDate object in a different textual format, use the DateTimeFormatter class. Search Stack Overflow for more info as it, like the rest of your Question, has been covered many times already on Stack Overflow. Do search Stack Overflow before posting.



          Tip: Generally best to use a PreparedStatement in your JDBC work. One major benefit is thwarting SQL Injection security attacks.




          About java.time



          The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.



          To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.



          The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.



          You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



          Where to obtain the java.time classes?




          • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

            • Java 9 adds some minor features and fixes.



          • Java SE 6 and Java SE 7

            • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.



          • Android

            • Later versions of Android bundle implementations of the java.time classes.

            • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


          The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.






          share|improve this answer















          tl;dr



          myPreparedStatement
          .setObject(
          LocalDate.parse( "2019-01-23" )
          ) ;



          DATE in MySQL is date-only



          The DATE type in MySQL is a date-only value, without time-of-day and without time zone.



          Excerpting from MySQL 8.0 documentation:




          The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.




          Use a date-only type in Java for data coming from a date-only type in your database. The java.util.Date class you are trying to use is not a date, it is a moment in UTC, a date with time-of-day and offset-from-UTC of zero, all tracked as a count of milliseconds from the first moment of 1970 in UTC. The misnaming of that class is only the first of many poor design choices made by those programmers. Move on to java.time classes instead. Stop using Date.




          MM = month number, not name



          Your format of "yyyy-MM-dd" is for a numeric month, not the string of month name shown in your example value of 25-March-2019.



          Avoid legacy date-time classes



          The SimpleDateFormat and Date classes are terrible, a wretched mess of bad design. They were supplanted years ago with the adoption of JSR 310, implemented in the java.time classes.



          Smart objects, not dumb strings



          Exchange objects with your database where possible, not text.



          As of JDBC 4.2, we can directly exchanged java.time objects with the database. For a date-only value, as with SQL-standard DATE type, use the java.time.LocalDate class.



          Apparently, your text inputs for date values is YYYY-MM-DD which is standard ISO 8601 format. The java.time classes use ISO 8601 formats by default. So no need to specify a formatting pattern.



          LocalDate localDate = LocalDate.parse( "2019-01-23" ) ;
          myPreparedStatement.setObject( … , localDate ) ;


          Retrieval.



          LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;



          localDate.toString(): 2019-01-23




          If you want to produce a string representing the value of that LocalDate object in a different textual format, use the DateTimeFormatter class. Search Stack Overflow for more info as it, like the rest of your Question, has been covered many times already on Stack Overflow. Do search Stack Overflow before posting.



          Tip: Generally best to use a PreparedStatement in your JDBC work. One major benefit is thwarting SQL Injection security attacks.




          About java.time



          The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.



          To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.



          The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.



          You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.



          Where to obtain the java.time classes?




          • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.

            • Java 9 adds some minor features and fixes.



          • Java SE 6 and Java SE 7

            • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.



          • Android

            • Later versions of Android bundle implementations of the java.time classes.

            • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


          The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 26 at 16:51

























          answered Mar 26 at 4:17









          Basil BourqueBasil Bourque

          127k36 gold badges427 silver badges599 bronze badges




          127k36 gold badges427 silver badges599 bronze badges























              2














              Java 7 and ThreeTen Backport



               DateTimeFormatter formatter
              = DateTimeFormatter.ofPattern("d-MMMM-uuuu HH:mm:ss", Locale.ENGLISH);
              String dateFromHtmlForm = "25-March-2019 22:43:55";
              LocalDateTime dateTime = LocalDateTime.parse(dateFromHtmlForm, formatter);
              // We are discarding the time of day and only saving the date
              java.sql.Date dateToSave = DateTimeUtils.toSqlDate(dateTime.toLocalDate());

              String insertSql = "insert into your_table (your_date_column) values (?);";
              try (PreparedStatement insertStatement
              = yourDatabaseConnection.prepareStatement(insertSql))
              insertStatement.setDate(1, dateToSave);
              int rowsInserted = insertStatement.executeUpdate();



              As has already been said, pass date objects to MySQL, not strings. In Java 8 and later these would have been LocalDate objects, but in Java 7 we will need to make do with the poorly designed java.sql.Date class. It’s still better than strings. And the conversion from LocalDate is straightforward.



              On Java 7 we can use java.time through the backport, ThreeTen Backport (ThreeTen for JSR-310). My imports are:



              import org.threeten.bp.DateTimeUtils;
              import org.threeten.bp.LocalDateTime;
              import org.threeten.bp.format.DateTimeFormatter;


              Why would we want to use an external library for this? There are pros and cons, of course. Advantages include:



              • java.time is so much nicer to work with than the old-fashoined Date and SimpleDateFormat and gives clearer code.

              • It’s future-proof: once you move to Java 8 or later, all you need to do is change your import statements (and discard the library and retest).

              Links




              • Oracle tutorial: Date Time explaining how to use java.time.


              • Java Specification Request (JSR) 310, where java.time was first described.


              • ThreeTen Backport project, the backport of java.time to Java 6 and 7.


              • ThreeTenABP, Android edition of ThreeTen Backport


              • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.





              share|improve this answer



























                2














                Java 7 and ThreeTen Backport



                 DateTimeFormatter formatter
                = DateTimeFormatter.ofPattern("d-MMMM-uuuu HH:mm:ss", Locale.ENGLISH);
                String dateFromHtmlForm = "25-March-2019 22:43:55";
                LocalDateTime dateTime = LocalDateTime.parse(dateFromHtmlForm, formatter);
                // We are discarding the time of day and only saving the date
                java.sql.Date dateToSave = DateTimeUtils.toSqlDate(dateTime.toLocalDate());

                String insertSql = "insert into your_table (your_date_column) values (?);";
                try (PreparedStatement insertStatement
                = yourDatabaseConnection.prepareStatement(insertSql))
                insertStatement.setDate(1, dateToSave);
                int rowsInserted = insertStatement.executeUpdate();



                As has already been said, pass date objects to MySQL, not strings. In Java 8 and later these would have been LocalDate objects, but in Java 7 we will need to make do with the poorly designed java.sql.Date class. It’s still better than strings. And the conversion from LocalDate is straightforward.



                On Java 7 we can use java.time through the backport, ThreeTen Backport (ThreeTen for JSR-310). My imports are:



                import org.threeten.bp.DateTimeUtils;
                import org.threeten.bp.LocalDateTime;
                import org.threeten.bp.format.DateTimeFormatter;


                Why would we want to use an external library for this? There are pros and cons, of course. Advantages include:



                • java.time is so much nicer to work with than the old-fashoined Date and SimpleDateFormat and gives clearer code.

                • It’s future-proof: once you move to Java 8 or later, all you need to do is change your import statements (and discard the library and retest).

                Links




                • Oracle tutorial: Date Time explaining how to use java.time.


                • Java Specification Request (JSR) 310, where java.time was first described.


                • ThreeTen Backport project, the backport of java.time to Java 6 and 7.


                • ThreeTenABP, Android edition of ThreeTen Backport


                • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.





                share|improve this answer

























                  2












                  2








                  2







                  Java 7 and ThreeTen Backport



                   DateTimeFormatter formatter
                  = DateTimeFormatter.ofPattern("d-MMMM-uuuu HH:mm:ss", Locale.ENGLISH);
                  String dateFromHtmlForm = "25-March-2019 22:43:55";
                  LocalDateTime dateTime = LocalDateTime.parse(dateFromHtmlForm, formatter);
                  // We are discarding the time of day and only saving the date
                  java.sql.Date dateToSave = DateTimeUtils.toSqlDate(dateTime.toLocalDate());

                  String insertSql = "insert into your_table (your_date_column) values (?);";
                  try (PreparedStatement insertStatement
                  = yourDatabaseConnection.prepareStatement(insertSql))
                  insertStatement.setDate(1, dateToSave);
                  int rowsInserted = insertStatement.executeUpdate();



                  As has already been said, pass date objects to MySQL, not strings. In Java 8 and later these would have been LocalDate objects, but in Java 7 we will need to make do with the poorly designed java.sql.Date class. It’s still better than strings. And the conversion from LocalDate is straightforward.



                  On Java 7 we can use java.time through the backport, ThreeTen Backport (ThreeTen for JSR-310). My imports are:



                  import org.threeten.bp.DateTimeUtils;
                  import org.threeten.bp.LocalDateTime;
                  import org.threeten.bp.format.DateTimeFormatter;


                  Why would we want to use an external library for this? There are pros and cons, of course. Advantages include:



                  • java.time is so much nicer to work with than the old-fashoined Date and SimpleDateFormat and gives clearer code.

                  • It’s future-proof: once you move to Java 8 or later, all you need to do is change your import statements (and discard the library and retest).

                  Links




                  • Oracle tutorial: Date Time explaining how to use java.time.


                  • Java Specification Request (JSR) 310, where java.time was first described.


                  • ThreeTen Backport project, the backport of java.time to Java 6 and 7.


                  • ThreeTenABP, Android edition of ThreeTen Backport


                  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.





                  share|improve this answer













                  Java 7 and ThreeTen Backport



                   DateTimeFormatter formatter
                  = DateTimeFormatter.ofPattern("d-MMMM-uuuu HH:mm:ss", Locale.ENGLISH);
                  String dateFromHtmlForm = "25-March-2019 22:43:55";
                  LocalDateTime dateTime = LocalDateTime.parse(dateFromHtmlForm, formatter);
                  // We are discarding the time of day and only saving the date
                  java.sql.Date dateToSave = DateTimeUtils.toSqlDate(dateTime.toLocalDate());

                  String insertSql = "insert into your_table (your_date_column) values (?);";
                  try (PreparedStatement insertStatement
                  = yourDatabaseConnection.prepareStatement(insertSql))
                  insertStatement.setDate(1, dateToSave);
                  int rowsInserted = insertStatement.executeUpdate();



                  As has already been said, pass date objects to MySQL, not strings. In Java 8 and later these would have been LocalDate objects, but in Java 7 we will need to make do with the poorly designed java.sql.Date class. It’s still better than strings. And the conversion from LocalDate is straightforward.



                  On Java 7 we can use java.time through the backport, ThreeTen Backport (ThreeTen for JSR-310). My imports are:



                  import org.threeten.bp.DateTimeUtils;
                  import org.threeten.bp.LocalDateTime;
                  import org.threeten.bp.format.DateTimeFormatter;


                  Why would we want to use an external library for this? There are pros and cons, of course. Advantages include:



                  • java.time is so much nicer to work with than the old-fashoined Date and SimpleDateFormat and gives clearer code.

                  • It’s future-proof: once you move to Java 8 or later, all you need to do is change your import statements (and discard the library and retest).

                  Links




                  • Oracle tutorial: Date Time explaining how to use java.time.


                  • Java Specification Request (JSR) 310, where java.time was first described.


                  • ThreeTen Backport project, the backport of java.time to Java 6 and 7.


                  • ThreeTenABP, Android edition of ThreeTen Backport


                  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 26 at 11:16









                  Ole V.V.Ole V.V.

                  35.5k7 gold badges44 silver badges62 bronze badges




                  35.5k7 gold badges44 silver badges62 bronze badges



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55349434%2fhow-to-properly-format-date-in-yyyy-mm-dd%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현