Parsing String to date

This is my function to convert a string into a desired output format.But my Date in the desired output format is coming out to be null.Could smeone plz point out my mistake.
Date getDateInDesiredFormat(String strInputDate,String strInputFormat,String strOutputFormat)
     try
       SimpleDateFormat sdfInput  = new SimpleDateFormat(strInputFormat);
       SimpleDateFormat sdfOutput = new SimpleDateFormat("MM-dd-yyyy");
       ParsePosition pos = new ParsePosition(0);
       Date dtInputDate=sdfInput.parse(strInputDate.trim(),pos);
       System.out.println(dtInputDate);
       String strFormattedDate=sdfOutput.format(dtInputDate);
       System.out.println(strFormattedDate);
       Date dtOutputDate=sdfOutput.parse(strFormattedDate.trim(),pos);
       if(dtOutputDate==null)
            System.out.println("dtOutputDate is null ");
       else
           System.out.println(dtOutputDate.toString());
       return dtOutputDate;
     catch (NullPointerException npex)
         return null;
      catch(Exception ex)
          return null;
   }This is how i am calling the function
Date date=getDateInDesiredFormat("Fri Sep 30 20:30:56 IST 2006","EE MMM d HH:mm:ss ZZZ yyyy","MM-dd-yyyy");
  }

You need to use the sdfInput object to parse the date and sdfOutput to format and print it (like you did before your 'if'):
SimpleDateFormat sdfInput  = new SimpleDateFormat(strInputFormat);
SimpleDateFormat sdfOutput = new SimpleDateFormat("MM-dd-yyyy");
Date dtInputDate=sdfInput.parse(strInputDate.trim());
String strFormattedDate=sdfOutput.format(dtInputDate);
System.out.println(strFormattedDate);the toString() you use in the else block uses a default format, not the one you specify.

Similar Messages

  • How to parse string to date in j2me?

    How to parse string to date in j2me?
    Please help me.

    Hi..
    String dyStr = "20";
    String mtStr = "1";
    String yrStr = "1999";
    Calendar cal = Calendar.getIntstance();
    int dy = Integer.parseInt(dyStr);
    int mt = Integer.parseInt(mtStr);
    int yr = Integer.parseInt(yrStr);
    cal.set(Calendar.DATE, dy);
    cal.set(Calendar.MONTH, mt);
    cal.set(Calendar.YEAR, yr);
    OK?

  • How to parse string to date with defualt format?

    is there any possibilities to parse a string to date if we don't specify the format in SDF?
    In database we have different formats and we need to convert each one convert to date with common format(something like default), is there any possibilities to do in java?

    jwenting wrote:
    Tolls wrote:
    ColinAtWork wrote:
    SumantK wrote:
    In database we have different formats and we need to convert each one convert to date with common format(something like default), is there any possibilities to do in java?Why don't you store the date in the database as a DATE datatype then you can format anyway you like??Because some people seem to fear DATEs and prefer the supposed comforts of a VARCHAR2...after all, who knows what murky goings on occur with a DATE, but at least a VARCHAR2 is readable, or something like that anyway.Just because some people don't know how to work with DATE fields (which is the real reason for their "fear" doesn't mean you shouldn't use them.
    They're the appopriate solution, so use it.Often but not always true.
    For example neither MS SQL Server nor Oracle timestamp types will store the resolution capable with the Java Date type. So if one wants to maintain all of that resolution one requires either a varchar or two columns.
    And although I haven't been able to confirm it (recently at least) at one time one of the Oracle drivers had a bug that a timestamp would wipe out following columns. For that one either one was left with having only a single timestamp as the last column or using a varchar.

  • Any easy way to parse string to date?

    I need get data from process instance and pass it to web service.
    The process instance is xmlObject and one field is date type. The value read from xmlObject is "2011-09-13T20:10:00Z"
    Is there any easy way to convert it to Date?
    Thanks,

    Hi
    Use date format to convert the string to date
    Example:
    String dateString = "Nov 4, 2003 8:14 PM";
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
    Java.Util.Date date = format.parse(dateString);
    display("Formated Date: " + date);
    Bibhu

  • SimpleDateFormat: Parse String To Date

    Hi
    I'm trying to parse Date-String to Date. But the Date-String I want to parse is embedded in a Text like:
    Bla bla bla bla bla bla 2004-05-05 bla bla bla bla bla.
    So I tried the attached Class to solve the problem, but it didn't work.
    Any ideas?
    Thanks Bona
    public class Test {
    private static SimpleDateFormat dateFormat = new SimpleDateFormat();
    private String text;
    private Date date;
    public Test() {
    /ry {
    text = "Bla bla bla bla bla bla 2004-05-05 bla bla bla bla bla.";
    date = toDate(text, "yyyy-MM-dd");
    System.out.println("Datum: "+date);
    } catch (ParseException pe) {
    System.out.println(pe.getMessage());
    public static void main(String[] args) {
    Test test1 = new Test();
    public static Date toDate(String dateString, String dateFormatPattern)
    throws ParseException {
    Date date = null;
    dateFormat.applyPattern(dateFormatPattern);
    dateFormat.setLenient(true);
    date = dateFormat.parse(dateString);
    return date;
    }

    Well, you need to extract the date pattern from that String.
    You can use regular expressions to do that. See theRegex package for info on how to do that.
    BTW - AFAIK, lenient date parsing means, that the parser accepts stuff that matches the pattern, but contains illegal values like "2004-02-30" ...

  • Having problems parsing String to Date

    Hello,
    Could someone please explain to me why the following code snippet parses the day and year correctly but returns the month as January regardless of which date I supply?
    SimpleDateFormat format = new SimpleDateFormat("M/D/y");
    try { Date date = format.parse("5/5/2000"); }
    catch (ParseException e) {}          
    System.out.println(date.toString());
    // returns --> Wed Jan 05 00:00:00 PST 2000

    Refer to http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html
    > SimpleDateFormat format = new SimpleDateFormat("M/D/y");Capital 'D' indicates Day in year. So day 5 in your example refers to the fifth day in Jan. Use small 'd', which indicates Day in month ...
    Cheers

  • Date string to Date object

    Hi
    How would i go about parsing some date strings in DD/MM/YYYY
    format into a date objects. I am sure its an easy problem but i
    cant find a simple way to do it as most of the API's want it a
    differnt format like MM/DD/YYYY
    Thanks for any help

    Hi,
    in the actionscript 3.0 cookbook there is a class DateFormat
    described, which allows to parse strings to date objects.
    You can download the code of the dateformat.as from here .
    http://www.rightactionscript.com/ascb/
    best regards,
    kcell

  • Facing Problem in parsing a string to date

    Hi,
    I was trying to change a string into date with date format ("EEEE,MMM,d,h:mm") but I always get the year as 1970.
    here is my code
    String strDate="Saturday,Jan 19 7:31";
    String dateFormat3="EEEE,MMM,d,h:mm";
         try {
         DateFormat myDateFormat = new SimpleDateFormat(dateFormat3);
         result1=myDateFormat.parse(strDate);
    catch(ParseException pe) {
                System.out.println("ERROR: could not parse date in string \"" +
            }any solution for it.

    This is my actual code
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    public class TestingDate {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              String dateFormat="EEEE, MMM d h:mm a";
              Date test=new Date(2007,0,19, 19, 31);
              System.out.println(" original date is "+test);
              String stringResult=DateToString(test,dateFormat);
              System.out.println("Date to string is "+stringResult);
              Date dateResult=stringToDate(stringResult,dateFormat);
              System.out.println(" String to date is "+dateResult);
              String stringResult2=DateToString(dateResult,dateFormat);
              System.out.println(" Date to string  is "+stringResult2);
    public static String DateToString(Date test, String dateFormat) {
             String result = null;
             try {
                  DateFormat myDateFormat = new SimpleDateFormat(dateFormat);
                     result = myDateFormat.format(test);
                     //System.out.println(" reslut date is "+result);
              } catch (Exception e) {
                   System.out.println(" Exception is "+e);
              return result;
    public static Date stringToDate(String strDate,String dateFormat1){
         Date result1=null;
         try {
              DateFormat myDateFormat = new SimpleDateFormat(dateFormat1);
              result1=myDateFormat.parse(strDate);
         catch(Exception e){
              System.out.println(" exception is "+e);
         return result1;
    }I am facing problem in getting the actual date. Please suggest the solution.

  • I need help parsing a  swift data string

    i need to parse swift financial data
    is there a way to use split or stringtokenizer for ::
    and keep the :: as part of the new seperated data.
    i want to put each string starting with :: on a seperate line in a text box.
    i gave up and tried it with a loop and a stringbuffer , and indexof.
    if (line.indexOf("::") == Strpos ){
    frame.jTextArea1.append(displayline.toString());
    displayline = new StringBuffer();
    displayline.append(line.substring(Strpos, (Strpos + 2)));
    Strpos += 2;
    if (line.indexOf("::") != Strpos ) {
    displayline.append(line.substring(Strpos, Strpos + 1));
    System.out.println( displayline);
    Strpos++;
    but i cant get that to work either.
    if anyone knows how to parse swift data please give me your email address.
    i've been doing it in cobol for 15 yrs and i just cant get the cobol techniques to translate to java.
    thanks.

    as i said
    i am really a cobol guy
    and yes as you see i did try to use indexof in my code.
    but there must be something about indexof that i'm not getting.
    it works the first time in the loop but then as i increment my start position(strpos)
    the indsex of no longer works.
    am i using the correct technique to increment the start position thru the string buffer.
    thanks guys.

  • Parsing today's date into a String

    How can I parse today's date into a String using this format: dd.mm.yyyy??? I taken a look at SimpleDateFormat, but I couldn't figure it out...
    Herman Svensen

    Hi Herman
    this is copied from the api docs:
    // Format the current time.
    SimpleDateFormat formatter
         = new SimpleDateFormat ("yyyy.MM.dd G 'at' hh:mm:ss a zzz");
    Date currentTime_1 = new Date();
    String dateString = formatter.format(currentTime_1);
    http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html
    So what is the problem to figure out?

  • Regarding conversion of String to Date

    Hi
    Ravi here and I am getting the following exception when i am working with String to date conversion.As i am working in LAN this code is working for all others .This problem is with my system only.This is not supporting with yyyy-MM-dd format.One more thing in my system only we installed VisualStudio.Is that a problem for this exception.I am using Myeclipse
    Plzzzzzzzzzzz help me I got strucked .
    Thanks in advance
    Code:
    public void testSaveDates() throws HibernateException, ParseException{
    try{
    Date date=new Date();
    String str1 ="2006-05-06";
    Date dateFormatter = new SimpleDateFormat("yyyy'-'MM'-'dd").parse(str1);;
    System.out.println(dateFormatter);
    catch(Exception e){
    e.printStackTrace();
    Exception:
    java.text.ParseException: Unparseable date: "2006-05-06"
         at java.text.DateFormat.parse(DateFormat.java:335)
         at chaitanya.MyTest.testSaveDates(MyTest.java:282)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at junit.framework.TestCase.runTest(TestCase.java:154)
         at junit.framework.TestCase.runBare(TestCase.java:127)
         at junit.framework.TestResult$1.protect(TestResult.java:106)
         at junit.framework.TestResult.runProtected(TestResult.java:124)
         at junit.framework.TestResult.run(TestResult.java:109)
         at junit.framework.TestCase.run(TestCase.java:118)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:421)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:305)
         at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:186)

    Date date=new Date();You don't need this line.
    Date dateFormatter = new
    er = new
    SimpleDateFormat("yyyy'-'MM'-'dd").parse(str1);;As already told, you don't need the single quotes. And you don't need two semi-colons - that's unnecessary.
    I just wrote a sample code to test that out. Check it and see for yourself.
    import java.text.SimpleDateFormat;
    public class Test {
         public static void main(String[] args) throws Exception {
              System.out.println(new SimpleDateFormat("yyyy-MM-dd").parse("2005-04-18"));
              System.out.println(new SimpleDateFormat("'yyyy'-'MM'-'dd'").parse("2005-04-18"));
    }Output:
    Mon Apr 18 00:00:00 EDT 2005
    Exception in thread "main" java.text.ParseException: Unparseable date: "2005-04-18"
            at java.text.DateFormat.parse(DateFormat.java:335)
            at Test.main(Test.java:6)I wonder why it is not feasible to write a quick sample code.

  • Need info on SimpleDateFormat, Converting String to Date

    I'm a newbie and doing a conversion of a string to a date and it's adding a little less than 11 minutes. I know I'm missing something really simple but as I read it I ought to be able to convert "20030125 084539.637696" to Sat Jan 25 08:45:39 not 8:56! Also, for the time being I'm ignoring the zulu 'Z' because I can't find a pattern that'll take it.
    System.out.println("INFO:MetadataExtractorBean::filestarttime:" + filestarttime);
    filestarttime = filestarttime.replace("Z","");
    System.out.println("after filestarttime.replace(Z,null) filestarttime:" + filestarttime);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd hhmmss.SSSSSS");
    Date convertedDate = dateFormat.parse(filestarttime);
    System.out.println("after dateFormat.parse(filestarttime) convertedDate:" + convertedDate);
    INFO:MetadataExtractorBean::filestarttime:20030125 084539.637696Z
    after filestarttime.replace(Z,null) filestarttime:20030125 084539.637696
    after dateFormat.parse(filestarttime) convertedDate:Sat Jan 25 08:56:16 EST 2003
    Can someone help me with a) why it doesn't remain 8:45, and b) how to modify the pattern to be able to parse a zulu date. Thanks in advance.

    import java.text.*;
    public class ParsingExample {
        public static void main(String[] args) throws ParseException {
            String s = "20030125 084539.637";
            SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd HHmmss.SSS");
            System.out.println(f.parse(s));
    }Your round up was because ".637696" was taken to mean 637,696 milliseconds. SimpleDateFormat doesn't have a way to accept microseconds, and anyway, java.util.Date only has millisecond precision. I also changed "hh" to "HH" because I assume this is with a 24 hour clock.
    edit: you can tell your date format not to do these roll ups by setting:
    f.setLenient(false);

  • Problem in  Converting String to Date

    Hi All,
    I am having one String
    String date = "2006-01-17 15:19:57.0"
    I want to parse this String into Date object.
    I will really appriciate if somebody helps me out.
    Thanks.

    You're specifying a 'T' and a timezone in your format, but they're not present in the string you're parsing.
    I'm assuming from the way you're printing out the date, that your thinking is along these lines: "sdfInput will parse the input string, no matter what format it's in, and will produce a Date object. That Date object wil have the format specified in sdfInput."
    This is wrong on a couple of fronts:
    1) DateFormat doesn't magically figure out what format it's supposed to use for the String it's parse()ing. The String has to match the DF's format.
    2) Dates don't have formats. Only Strings do. A Date object is just a long. There's no relationship whatsoever between the Date that you get from parse() and the format that was used to produce it. When you print out a Date as you're doing, its toString method is called, which in turn uses a default format for your Locale.
    If you want to turn a date string in one format into a date string in another format, use two different DateFormat objects with two different formats. Date date = df1.parse(inputString);
    String outputString = df2.format(date);

  • Conversion of string into date????????????

    Can anyone tell how to convert a String into date??
    if the string is in the format "Thu Mar 25 17:11:34 GMT+05:30 2004"
    i have converted it. code is
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d yyyy HH:mm:ss");
         dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
    Date date = null;
    try
              //date = dateFormat.parse(new Date().toString());
              date = dateFormat.parse(dateLine);
         catch(ParseException ex)
    but i am not able to specify the year.
    so when i getYear on the new Date it return 1970.

    @duffymo, I'm pretty sure "d" is good for a two digit date, "dd" gives you zero-padding.
    The problem, presumably, is that the format string "EEE MMM d yyyy HH:mm:ss" does not match the actual format "Thu Mar 25 17:11:34 GMT+05:30 2004".
    The correct format string would be "EEE MMM d HH:mm:ss z yyyy"

  • Formatting incoming string with date/time classes?

    Hello,
    In the software I am writing currently I am @ a certain point talking to an external device. sending requests, receiving responses.
    One of the things I find in the response is "20090429094222", as a string.
    I cannot change anything to that, thats the way I get it from the device, so thats where I'll have to start with.
    As you could probably guess this is a date and a time. Now my question. Is there a good way to format this from 20090429094222
    to
    2009-04-29 09:42:22
    using date and or time classes, not using String operations?
    Thanks in advance.

    I found a class containing 2 functions who do exactly what I need, for those intrested:
    public static Date convertStringToDate(String txtFormat, String txtDate) {
            DateFormat dateFormat = new SimpleDateFormat(txtFormat);
            Date date =  dateFormat.parse(txtDate);
            return date;
    public static String formatDate(Date date, String txtFormat) {
            DateFormat dateFormat = new SimpleDateFormat(txtFormat);
            String txtDate = dateFormat.format(date);
            return txtDate;
        }Using them this way gives me exactly what I want:
    Date dt = DateUtil.convertStringToDate("yyyyMMddHHmmss", incomingDateSTring);
    String newDateString = DateUtil.formatDate(dt, "yyyy-MM-dd HH:mm:ss");Problem solved, thanks alot to those who gave me some explanation on the problem.

Maybe you are looking for

  • WBS, Business Area and Profit Center not flowing in GR/IR Account

    Hello Experts, I have come across a very strange situation. I have two MIGO documents which are showing different posting characteristics: 1) FI Document 5000000553 In this document, the Business area and profit center is flowing in GR/IR Clearing Ac

  • Handling exception thrown by parseEscapedXML function

    Hi, I am using parseEscapedXML function to parse an xml string in the below format . <parameters><item id="" value=""/><item id="" value=""/></parameters> The exception thrown when input is in incorrect xml format is not caught using catchAll. Kindly

  • Powershell dynamic T-SQL (string and variable contatenation)

    Hi, How do I build a dynamic t-sql through Powershell? $Query2 = @"        INSERT INTO [dbo].[Maint_Log] ([Servername],[StartTime],[Status])      VALUES (" + $MaintLogRecords.Server + " ,"  + [Datetime]$MaintLogRecords.Startime + " , "  + $MaintLogRe

  • Sincyng with mac os and windows

    Hi, I have a mac book pro with mac os at home, and a pc with windows at work, is it possible to sync my iphone with both computwers?

  • Bindings problem (EJB3 - ADF  Faces)

    Hi Forum, I have a static fieald in a entityBean (EJB3) with its accessors: private static Double totalQty; I have this method in a session bean: public Double TotalsSaticValues(){ return VOrderLinesFulladj.getTotalCHF(); And I want to show the value