How to convert a String into a date in yyyy-MM-dd using SimpleDateFormat?

Hi Guys,
I am using the following code
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class ValiDATE {
     private static boolean validateDateFormat(String strDate) {
          try {
               SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd");
               try {
                    formatter.setLenient(false);
                    formatter.parse(strDate);
               catch (ParseException e) {
                    // invalid date/datetime format          
                    return false;
          catch (Exception ignored) {
          return true;
     public static void main(String args[]){
          System.out.println(validateDateFormat("11111-11-11"));          
}In the above snippet even if I pass the string parameter as "11111-11-11" it returns a new date and hence prints TRUE in the console, but I want the date to be in yyyy-MM-dd format that is no of years shouldn't exceed 4 digits in all.
I don't want to use RegEx, I know this can be done using SimpleDateFormat, but would like to know how that can be done.
I think it has to do something with this . ( [http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html#year|http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html#year] )
Regards
AR

Java.slogger wrote:
Yeah I have gone through the javaDoc and it says For formatting, if the number of pattern letters is 2, the year is truncated to 2 digits; otherwise it is interpreted as a number. The important part is:
JavaDoc:
Any other numeric string, such as a one digit string, a three or more digit string, or a two digit string that isn't all digits (for example, "-1"), is interpreted literally.
Do you know any workarounds else is using a Regex is the best approach?I don't see this as a problem. Everything behaves as designed and as is sensible.
So if you want to avoid dates with 5-digit numbers, I'd add something like:
if (parsedDate.after(CUTOFF_DATE)) {
  throw new OhNoesThisIsEvilException("!");
}

Similar Messages

  • How to convert a string into orcle date format

    i need some information about converting string into date format.i have string like '20-SEP-05' .so we have to convert into date formate like yy-mm-dd' (2005-09-20).how can we do it.

    Here's some code to help. I can't remember what method uses what format though
      public static java.sql.Date sqlDateValueOf( String dateString ) {
        String stringDate = null;
        if ( dateString == null || dateString.length() < 10 ) return null;
        String strDay = "";
        String strMonth = "";
        String strYear = "";
        if ( dateString.substring(4,5).equals( "-" ) ) {
          strDay = dateString.substring(8, 10);
          if ( strDay.length() < 2 ) strDay = "0" + strDay;
          strMonth = dateString.substring(5, 7);
          strMonth = dateString.valueOf(Integer.parseInt(strMonth) - 1);
          if ( strMonth.length() < 2 ) strMonth = "0" + strMonth;
          strYear = dateString.substring(0, 4);
          stringDate = strDay + "-" + strMonth + "-" + strYear;
        else if ( dateString.substring(2,3).equals( "-" ) ) {
          strDay = dateString.substring(0, 2);
          if ( strDay.length() < 2 ) strDay = "0" + strDay;
          strMonth = dateString.substring(3, 5);
          strMonth = String.valueOf(Integer.parseInt(strMonth) - 1);
          if ( strMonth.length() < 2 ) strMonth = "0" + strMonth;
          strYear = dateString.substring(6, 10);
          stringDate = strDay + "-" + strMonth + "-" + strYear;
        Calendar cal = Calendar.getInstance();
        cal.set( Calendar.YEAR, Integer.parseInt( strYear ) );
        cal.set( Calendar.MONTH, Integer.parseInt( strMonth ) );
        cal.set( Calendar.DAY_OF_MONTH, Integer.parseInt( strDay ) );
        java.sql.Date outDate = new java.sql.Date( cal.getTimeInMillis() );
        return outDate;
      public static String toDateString( java.util.Date date) {
        if ( date == null || date.toString().length() < 10 ) return null;
        String outDate = "";
        SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        outDate = df.format( date );
        return outDate;
      public static String toDateString( java.sql.Date date) {
        if ( date == null || date.toString().length() < 10 ) return null;
        String outDate = "";
        SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        outDate = df.format( date );
        return outDate;
      public static String toDateString( java.sql.Date date, String format) {
        if ( date == null || date.toString().length() < 10 ) return null;
        String outDate = "";
        SimpleDateFormat df = new SimpleDateFormat( format );
        outDate = df.format( date );
        return outDate;
      public static String toDateString( java.sql.Timestamp date) {
        if ( date == null || date.toString().length() < 10 ) return null;
        String outDate = "";
        SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        outDate = df.format( date );
        return outDate;
      }

  • How to convert a string from lower case to upper case withour using transla

    Hi all,
    how to convert a string from lower case to upper case withour using translate,
    Thanks in Advance,
    Reddy

    Refer to this related thread
    Re: hi guys this very urgent please help

  • How to convert a optionset into multi selection picklist in crm 2011 using javasacript??

    hi,
    where user want to select not only one but multiple value
    from a pick list. I tried  examples but it shows some errors.
    How  to do it??

    Hey I meet a problème on my development see my result :
    link : https://social.microsoft.com/Forums/getfile/652331
    a multiple select list on my crm 2013 I do this process on this forum :
    link : https://social.microsoft.com/Forums/en-US/2db47a59-165d-40c9-b995-6b3262b949eb/how-to-convert-a-optionset-into-multi-selection-picklist-in-crm-2011-using-javasacript?forum=crmdevelopment
    my development :
    // var_sc_optionset >> Provide schema-name for Option Set field
    // var_sc_optionsetvalue >> Provide schema-name for field which will store the multi selected values for Option Set
    // OS >> Provide Option Set field object
    // OSV >> Provide text field object which will store the multi selected values for Option Set
    //Method to convert an optionset to multi select Option Set
    function ConvertToMultiSelect(var_sc_optionset, var_sc_optionsetvalue, OS, OSV)
    if( OS != null && OSV != null )
    OS.style.display = "none";
    Xrm.Page.getControl(var_sc_optionsetvalue).setVisible(false);
    // Create a DIV container
    // var addDiv = document.createElement("<div style='overflow-y:auto; color:#000000; height:160px; border:1px #6699cc solid; background-color:#ffffff;' />");
    var addDiv = document.createElement("div");
    addDiv.style.overflowY = "auto";
    addDiv.style.height = "160px";
    addDiv.style.border = "1px #6699cc solid";
    addDiv.style.background = "#ffffff";
    addDiv.style.color = "#000000";
    OS.parentNode.appendChild(addDiv);
    // Initialise checkbox controls
    for( var i = 1; i < OS.options.length; i++ )
    var pOption = OS.options[i];
    if( !IsChecked( pOption.text , OS, OSV) ){
    // var addInput = document.createElement("<input type='checkbox' style='border:none; width:25px; align:left;' />" );
    var addInput = document.createElement("input" );
    addInput.setAttribute("type","checkbox");
    addInput.setAttribute("style","border:none; width:25px; align:left;");
    else {
    // var addInput = document.createElement("<input type='checkbox' checked='checked' style='border:none; width:25px; align:left;' />" );
    var addInput = document.createElement("input" );
    addInput.setAttribute("type","checkbox");
    addInput.setAttribute("checked","checked");
    addInput.setAttribute("style","border:none; width:25px; align:left;");
    // var addLabel = document.createElement( "<label />");
    var addLabel = document.createElement( "label");
    addLabel.innerText = pOption.text;
    // var addBr = document.createElement( "<br />"); //it's a 'br' flag
    var addBr = document.createElement( "br"); //it's a 'br' flag
    OS.nextSibling.appendChild(addInput);
    OS.nextSibling.appendChild(addLabel);
    OS.nextSibling.appendChild(addBr);
    ///////Supported functions
    // Check if it is selected
    function IsChecked( pText , OS, OSV)
    if(OSV.value != "")
    var OSVT = OSV.value.split(";");
    for( var i = 0; i < OSVT.length; i++ )
    if( OSVT[i] == pText )
    return true;
    return false;
    // var_sc_optionsetvalue >> Provide schema-name for field which will store the multi selected values for Option Set
    // OS >> Provide Option Set field object
    // Save the selected text, this field can also be used in Advanced Find
    function OnSave(OS, var_sc_optionsetvalue)
    var getInput = OS.nextSibling.getElementsByTagName("input");
    var result = '';
    for( var i = 0; i < getInput.length; i++ )
    if( getInput[i].checked)
    result += getInput[i].nextSibling.innerText + ";";
    //save value
    control = Xrm.Page.getControl(var_sc_optionsetvalue);
    attribute = control.getAttribute();
    attribute.setValue(result);
    I have to do 2 field one is option list field and the second is textfield, 
    option list field : new_books
    textfiled          : new_picklistvalue
    my js is on onload event see : 
    link : https://social.microsoft.com/Forums/getfile/652333
    thanks you for you'r help 

  • Converting a string into mySQL date format

    I have a bit of code that collects data values from a bean and I want it to then insert this into a mySQL database. My string is in the format "23/12/1983", how can i put this into a date field in my database? The bit of code I have got so far looks like this...
    String month = formHandler.month + "/";
    String day = formHandler.day + "/";
    String year = formHandler.year ;
    StringBuffer sb = new StringBuffer();
    sb.append(day);
    sb.append(month);
    sb.append(year);
    String myDate = sb.toString();myDate is the value that I want to go into the database

    Limo2kz,
    The key to inserting a date into a database is to convert the date string into an SQL friendly format. i.e. yyyy-MM-dd.
    One way of doing this is as follows:
    SimpleDateFormat NICE_DATE_FORMAT =
    new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat SQL_DATE_FORMAT =
    new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();
    try {
    date = NICE_DATE_FORMAT.parse(dateString);
    } catch (ParseException pe) {
    pe.printStackTrace();
    String sqlDate = SQL_DATE_FORMAT.format(date);
    Now it is just a matter of creating the insert statement like normal, and making sure that the date string is in quotes.
    I hope that helps.
    Damian Sutton

  • How to convert a string value to date

    Dear All,
    I am new to powershell script, i was trying to store a Ad user password set date to a variable add, add a number of days to get the expire date.
    but when i try to convert the variable to date value, I am getting the error as below.
    Please help me......
    PS C:\script> $passwordSetDate = (get-aduser user1 -properties * | select PasswordLastSet)
    PS C:\script> $passwordSetDate
    PasswordLastSet
    7/15/2014 8:17:24 PM
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    Cannot find an overload for "ParseExact" and the argument count: "3".
    At line:1 char:1
    + $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodException
        + FullyQualifiedErrorId : MethodCountCouldNotFindBest
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)

    Dear All,
    I am new to powershell script, i was trying to store a Ad user password set date to a variable add, add a number of days to get the expire date.
    but when i try to convert the variable to date value, I am getting the error as below.
    Please help me......
    PS C:\script> $passwordSetDate = (get-aduser user1 -properties * | select PasswordLastSet)
    PS C:\script> $passwordSetDate
    PasswordLastSet
    7/15/2014 8:17:24 PM
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    Cannot find an overload for "ParseExact" and the argument count: "3".
    At line:1 char:1
    + $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodException
        + FullyQualifiedErrorId : MethodCountCouldNotFindBest
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    In your post you ask how to convert a string value to a date.  The value returned from the Get-AdUser is already a date.  It does not need to be converted.
    Bill has sshown one way to convert a date to a string and there are other methods.  You need to clarify your question.
    If you are really trying ot convert strings to dates then you can start with this:
    [datetime]'01/21/1965 13:33:23'
    Most date strings aer autodetected by the class.
    ¯\_(ツ)_/¯

  • XML: How to convert xml string into Node/Document

    I have a string in xml form.
    <name>
    <first/>
    <second/>
    </name>
    I want to convert this string into DOM Node or Document.
    How can I do this?
    Any help or pointer?
    TIA
    Sachin

    Try this :
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new org.xml.sax.InputSource(new StringReader(strXml)));Hope this helps.

  • How to convert Java string into XML one?

    With SAX I can parse an xml file, but I should create xml file by hands.
    Ok, it's simple, but how to encode java string into XML constant
    like "Hello & goodby" into "Hello & goodby" ?
    Is there a standard method for such special xml characters?

    If you are creating your XML "by hand" then just make sure your hands know that you have to do that. It isn't difficult to write a Java method to do it, if "by hand" means "in Java code". Otherwise your XML is not well-formed. And as far as I know there is no package that takes ill-formed XML and fixes it up.

  • How to convert a string into an objects name?

    Hi
    I have the following problem;
    I have a string
    String a = "e1"
    and a method
    call(Event e1) that calls the "Event" class with object the name of the string a.
    How can I convert the strings name into an object so as to use it in the "call" method?
    Any ideas?
    Thanks in advance

    I don't know if this helps you, but you can do things like this.
    String a = "com.example.SomeEvent";
    //Instantiate com.example.SomeEvent
    Object o = Class.forName(a).newInstance();SomeEvent must have a non-argument constructor for this to work.
    Class that will be instantiated depens on runtime value of String a, and can be different across different executions of the program.

  • How to convert a string into a collection of KeyEvents

    I'm working on a program that must interact with a 3rd party application (closed to me, I have no access to the code or anything like that). I have been unable to send data to the program by getting its OutputStream. The only thing that has worked was using a Robot object to send individual key events (i.e. robot.keyPress(KeyEvent.VK_A);). Therefore I'm looking to convert a string (many different strings actually) into a collection of their associated KeyEvents so I can send them to the other application. Does anyone know a good way of doing it, or is anyone able to help me with using the OutputStream?
    Thank you!
    (The 3rd party application is Attachmate InfoConnect, a Unisys terminal emulation program that I have to use to access a mainframe).

    Here is a code sample.     public void checknumber(int vsize){
    int total;
    String anum;
    anum = tf2.getText();
    validnumber = true;
    lines2combine = 1;     //default (an integer)
    recs2make = 1;          //default
    try{
    lines2combine = Integer.parseInt(anum);
    catch (NumberFormatException e){
              System.out.println("Entry for lines to combine not numeric");
         validnumber = false;
         d1Title = "Data Entry Error";
         d1Txt = "For number for lines to combine;";
         d2Txt = "Enter a number.";
         doMessage();

  • How to convert multiple rows into colmun data?

    Hi all
    ODI has fuction that covert multiple rows form a file into colmun data?
    Source:customer.txt
    001,Scott
    001,Man
    001,23
    002,Lincon
    002,Man
    002,21
    objective Target:customer
    ID Name Sex Age
    001 Scott Man 23
    002 Lincon Man 21
    If there is no this fuction,how can I do this in ODI?
    Thanks in advance.
    Agui

    Hi, Sanjeev,
    What you requested is called String Aggregation.
    Like most other things, the best way to do it depends on your version of Oracle.
    The following site shows several different ways to do string aggregation:
    http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php'
    The user-defined function (often called STRAGG) that Charles mentioned is my favorite, in versions between 9.1 and 11.1.

  • How to convert character string into ascii format correctly

    dear all
    I'm using encryption technique in my application(oracle formas 6i). character stream convert to the ascii format and add some numeric value and again convert to the character format
    >>>>
    here I'm using ASCII and CHR functions.
    >>>>
    .net program also using same algorithm to encrypt this password.....finally both the character strings are not equel.(This happens if the character string's ascii value greater than 127. otherwise both are equel).
    pls give me a solution for this
    thanks and regards
    buddhike

    hir dear
    do u want to encrypt & dcrypt your password.which version of oracle you are using
    first store these procedure in Oracle Databases: dbms_obfuscation_toolkit, dbms_crypto, Transparent Data Encryption
    now u can use these procedure to encrypt & dcrypt your password
    if you any query about those procedures you can ask me
    best regard
    amk

  • How to convert a string into xml file

    Hi,
    i have a string . the string contain fully formated xml data. i mean my string like below
    <?xml version="1.0"?>
    <PARTS>
       <TITLE>Computer Parts</TITLE>
       <PART>
          <ITEM>Motherboard</ITEM>
          <MANUFACTURER>ASUS</MANUFACTURER>
          <MODEL>P3B-F</MODEL>
          <COST> 123.00</COST>
       </PART>
       <PART>
    ......................i want to convert it into an xml file
    can u help me?
    thank u

    Thank you Paul Clapham,
    and sorry ..
    i have some other doubt.. regarding xml
    i want to post an XML file from one server(Server_1) to other server.(Server_2)
    To generate an xml file i used DOM in Server_1.
    using xml.transform , StringWriter i converted it into String.
    I post the string to another server and there i will parse it.
    for that i write the code like below in servlet in server_1
    <form name=fn action=http://localhost:8080/server_2/parseXMl.do method=post>
    <input type=hidden name=xmlFile value="+Xmlstring+">
    <input type=submit >is this process is correct?
    Some of the turorial told that use web-services/XML-RPC
    but i new to both..
    I want to complete it using my knowledge only/
    Is it possible to do it?
    Or any other alternative?
    can help me?

  • How to convert a string into double?

    Hi. I'm having a string with 10340.8878 which is essentially a GPS latitude coordinate. I will need to break it up separately into double type 103,40 and 88.
    103 refers to the degree
    40 refers to the minutes
    88 refers to the seconds
    I will also need to perform a double conversion: the second separated double(40) divided by a factor of 60 and the third separated double(88) divided by a factor of 360.
    How can i go about doing this?
    Thanks!

    new Double(str).doubleValue();
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Double.html

  • How to turn a string into a date value

    Hi All,
    What is the best way to approach a date sorting issue I have?
    A web service that I consume returns a date column in a string
    format. Thus when the user clicks the column to sort a data grid by
    that date value it sorts incorrectly.
    I realize I could put a sort() on the grid or convert the
    data somehow. I am hoping several people can give me what would be
    considered a "best practice" from a code readability and
    performance point of view.
    Thannks in advance for your thoughts on this issue.

    you dont have to convert anything just implement function and
    asign it to Sort object's "compareFunction" property
    The compare function must have the following signature:
    function [name](a:Object, b:Object, fields:Array=null):int
    This function must return the following
    * -1, if a should appear before b in the sorted sequence
    * 0, if a equals b
    * 1, if a should appear after b in the sorted sequence
    inside that function you might need a tmp conversion but
    overall that should be it
    for example (function can look like this :
    if a===b) return 0;
    if(myStringToDateConvertor(a) > myStringToDateConvertor(m)
    ) return 1;
    if(myStringToDateConvertor(a) < myStringToDateConvertor(m)
    ) return -1;
    return 0;
    (remember sortField also has has compareFunction property but
    you dont need that one).

Maybe you are looking for

  • Fully embedding fonts in PDF

    Hi, I had a piece of information but I can't seem to find it anymore so I have to ask ... This is about understanding limitations of fully embedding fonts in a PDF (from Indesign Server). Actually it's about one limitation in particular. I know fonts

  • Lightroom 3 wont open

    i loaded lr 3 from a disk i got with my purchase of photoshop elements 10 ,it is a 30 day trial ,it loaded ok,but will noy open ,it says contact support ,i removed and reloaded it 2 times ,still nothing

  • Sharing I Photo books

    I recently completed a family reunion IPhoto book and would like to share it online. Is there a way to send it via email to others in my family so they can decide if they want to purchase it? Thanks.

  • Show error overrides a deprecated API ?

    hi, when my java program run, it shows, Note: D:\javaexample\myJavaPgm.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. what this error message. Can I ignore this warning ?. or how can i solve this warning

  • Best output for HD media player?

    I have a seven-hour project shot in high definition with the Sony PMW EX-1 at 1080i 60. All clips have been through Color and are now in Pro Res 422 HQ. There are six to eight tracks of audio as well. My goal is to output to a file to play on a media