Parsing datestring to GregorianCalendar on Solaris.

Hi There!
I?m parsing strings to GregorianCalendar object with the class SimpleDateFormat. The problem is that when I?m running on a Windows platform everything works out great but when I deploy it on a Solaris platform the parser parse it wrongly.
Heres the code:
java.util.TimeZone tz= null;
String timezonesettings= null;
String availableIds[]= null;
String timezone= null;
SimpleTimeZone zone= null;
java.text.SimpleDateFormat sdf= null;
int TZ_OFFSET= 1*60*60*1000;
try{
//get requested time zone from jsp page.
timezone= request.getParameter("timezone");
//pattern= "ww-yyyy"
pattern= request.getParameter("pattern");
//get requested datestring from client
date= request.getParameter("date");
loc= Integer.parseInt(request.getParameter("locale"));          
zone = new SimpleTimeZone(TZ_OFFSET, timezone);
zone.setStartRule(Calendar.MARCH,-1,Calendar.SUNDAY,2*60*60*1000);
zone.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2*60*60*1000);
sdf= new java.text.SimpleDateFormat(pattern,locale[loc]);
sdf.setTimeZone(zone);
sdf.setLenient(false);
gregdate= new GregorianCalendar(zone,locale[loc]);
gregdate.setTime(sdf.parse(date));
}catch(Exception e){
The thing is when i try to parse with the pattern "ww-yyyy" the parsing on a solaris platform always returns a the date with value 1 Jan. Why this??
Best regards
Niclas Rothman

It is a known bug:
http://developer.java.sun.com/developer/bugParade/bugs/4227284.html
See their work around.

Similar Messages

  • DateFormat parse method usage

    Hi all,
    I am using the following code to parse the date String object to Date Object -
    ======================================================================
    if(dateString == null || dateString.trim().equals(""))
    return null;
    DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT,
    Locale.getDefault());
    Date d = null;
    try
    dateFormatter.setLenient(false);
    d = dateFormatter.parse(dateString);
    catch(ParseException pe)
    e.printStackTrace();
    =================================================================
    This code works perfectly for all formats of String objects I give except for the format - "12/12/12/1" in which case it converts to following date object -
    "Wed Dec 12 00:00:00 IST 2012" although its an invalid date String.
    Please let me know how I could have correct validation done in such cases or if this is the right behavior for DateFormat class.
    Thanks in advance!!

    I'm not going to comment on how exactly the parse method does its business, but I can suggest you use a regex pattern to validate the input you will send the parse method.
    Here is some info from the CodeProject website on date validation(Note that this is aimed at .NET - but regex works the same in Java as it does in .NET [i think]):
    Dates: As with numbers, we need two validators: a key-press validator, and a completion validator. The key-press validator can be pretty simple, if we limit how our user enters the date. Let’s say that we want to validate for the U.S. date format mm/dd/yyyy. Here is a validator that will do that:
    ^([0-9]|/)*$
    The regex reads: “Match any string that contains a sequence of zero or more characters, where each character is either a digit or a slash.” This validator will give the user immediate feedback if they enter an invalid character, such as an ‘a’.
    Copy that regex to Regex Tester and give it a try. Note that the validation fails if the user enters dashes, instead of slashes, between the parts of the date. How could we increase the flexibility of our regex to accommodate dashes? Think about the question for a minute before moving on.
    All we need to do is add a dash to the alternates group:
    ^([0-9]|/|-)*$
    We could add other alternates to make the regex as flexible as it needs to be.
    The completion validator does a final check to determine whether the input matches a complete date pattern:
    ^[0-2]?[1-9](/|-)[0-3]?[0-9](/|-)[1-2][0-9][0-9][0-9]$
    The regex reads as follows: "Match any string that conforms to this pattern: The first character can be a 0, 1, or 2, and it may be omitted. The second character can be any number and is required. The next character can be a slash or a dash, and is required…” And so on. This regex differs from the ones we used before in that it specifies each character of the pattern—the pattern is more of a template than a formula.
    Note the first character of the regex: ‘[0-2]’. This character points out that we can limit allowable digits to less than the full set. We can also expand them; for example, ‘[0-9A-F]’ would allow any hexadecimal digit. In fact, we can use this structure, known as a character class, to specify any set of characters we want. For example, the character class ‘[A-Z]’ allows capital letters, and ‘[A-Za-z]’ allows upper or lower-case letters.
    Our date regex also points out some of the limitations of regex validation. Paste the date regex shown into Regex Tester and try out some dates. The regex does a pretty good job with run-of-the-mill dates, but it allows some patently invalid ones, such as ‘29/29/2006’, or ‘12/39/2006'. The regex is clearly not ‘bulletproof’.
    We could beef up the regular expression with additional features to catch these invalid dates, but it may be simpler to simply use a bit of .NET in the completion validator:
    bool isValid = DateTime.TryParse(dateString, out dummy);
    We gain the additional benefit that .NET will check the date for leap year validity, and so on. As always, the choice comes down to: What is simpler? What is faster? What is more easily understood? In my shop, we use a regex for the key-press validator, and DateTime.TryParse() for the completion validator.
    Oh - and there is another regex validator:
    ^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$
    which matches the yyyy-mm-dd date format and also validates month and number of days in a month. Could be improved as currently all leap year dates (yyyy-02-29) will validate.
    Sorry if I couldn't be of more help...
    Edited by: JoKiLlSyA on Oct 9, 2008 11:22 PM

  • C parser and deeply nested DTDs

    Your C parser is VERY fast :-),
    but I am having trouble with deeply nested DTDs.
    I can do DTD validation for an internal DTD and a single external DTD file.
    My problem is with a DTD which includes other DTDs to a depth of 5 levels.
    I am using the C XML parser v2.0.7 on Solaris 2.6.
    My XML docs & their DTD are for an OAG Purchase Order (056_add_po_003.dtd or 056_add_po_006.dtd).
    As these are OAG 'standards based' XML I cannot change the XML or DTD nesting.
    The screen dump & error message I get was:
    The error code after calling xmlinit() was >0<
    startDocument
    In line 20 of 056_add_po_006.xml:
    In line 31 of 056_add_po_006.dtd:
    In line 19 of oagis_resources.dtd [parameter entity RESOURCES]:
    In line 57 of oagis_segments.dtd [parameter entity SEGMENTS]:
    In line 4 of oagis_fields.dtd [parameter entity FIELDS]:
    LPX-00252: invalid entity replacement-text nesting
    The error code after calling xmlparse() was >252<
    =================
    Line 4 was:
    <!ELEMENT ACCTPERIOD %STRDOM;>
    The error is always at the same line of the oagis_fields.dtd dtd independent of whether I delete or move the 'ACCTPERIOD ELEMENT' that was at line 4.
    The sample OAG PO XML and its DTDs were:
    056_add_po_006.xml
    056_add_po_006.dtd
    oagis_domains.dtd
    oagis_extensions.dtd
    oagis_fields.dtd
    oagis_resources.dtd
    oagis_segments.dtd
    are available from OAG: http://www.openapplications.org/xml/loadform.htm
    You need to register to get the OAG docs but it is free.
    Thanks for your Help
    Doug.

    The error message file lpxus.msg has a detailed explanation:
    00252, 00000, "invalid entity replacement-text nesting"
    // *Cause: Markup included from an entity must nest/group properly, that
    // is, open/close markup must occur within the same entity.
    // For example,
    // <!DOCTYPE doc [ <!ENTITY e "</foo><foo>"> ]>
    // <doc><foo>&e;</foo></doc>
    // Is invalid since foo's start-tag occurs in the top-level
    // document, but the close-tag is provided by the "e" entity.
    // Both start and end must be provided by the same source.
    // *Action: Stay away from tricky nonsense such as the above, it's
    // not permitted.
    null

  • Encoding support for C++ parser.

    Hi,
    We are using XML C++ parser 2.0.4 in Solaris to handle our XML message. In order for us to support ISO-8859-1 or other encodings we need the NLS component of the ORACLE 8.0 DBMS software. We understand that in the later versions of the XML C++ parser NLS support will be rolled in with the C++ parser.
    In the interim for teams like ours not using ORACLE what are the options.
    Can we simply install unsupported ORACLE 8.0 demo software and be able to deliver to our customers with out any licence.
    Appreciate your help on this.
    Thanks,
    Vijay Kumar
    null

    Unfortunately, this turns out to not be as straightforward as shipping a single NLS data file. For now, if you don't have the Oracle NLS data files, you'll only be able to use ASCII xml files.

  • How to parse system date to return Date and in yyyy-MM-dd format?

    DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd");
    java.util.Date date = new java.util.Date ();
    String dateStr = dateFormat.format (date);
    try{
    Date date2 = dateFormat.parse (dateStr);
    }catch(ParseException pe){
    pe.printStackTrace();
    Actually, After parsing the date from string, again it is converted into dfault format i.e. 21 Jan 00.00.00 etc...
    But I want this parsing date in yyyy-MM-dd format and again to return date.
    Can anybody tell me how to do this?

    DateFormat dateFormat = new SimpleDateFormat
    ("yyyy-MM-dd");
    java.util.Date date = new java.util.Date ();
    String dateStr = dateFormat.format (date);
    try{
    Date date2 = dateFormat.parse (dateStr);
    }catch(ParseException pe){
    pe.printStackTrace();
    Actually, After parsing the date from string, again
    it is converted into dfault format i.e. 21 Jan
    00.00.00 etc...
    But I want this parsing date in yyyy-MM-dd format and
    again to return date.
    Can anybody tell me how to do this?A Date object does not have a format, it represents a moment in time. You can use SimpleDateFormat to return a String representing that moment in time in many formats - this does not change the Date object to have that format (which it cannot since it does not contain a format).

  • DateFormat.parse(String)

    can anybody tell me why I don't get a SHORT format:
    import java.util.*;
    import java.text.*;
    public class MyDate{
       public static void main(String[] args){
          Date date = makeDate("04/22/2003");
          System.out.println(date); // what i get looks more like FULL
        public static Date makeDate(String dateString){
           Date date = null;
           try {
              DateFormat fmt = DateFormat.getDateInstance(DateFormat.SHORT);
              date = fmt.parse(dateString);
          catch(ParseException e) {}
          return date;
    }Thank you.

    what I think is tripping you up is that a java.util.Date is not a String. It looks like you're thinking that you can format a java.util.Date object and somehow it is "11/23/2004" (or whatever) - but it's not - it's just a number. So, you have this String that you want to convert to a java.util.Date (which you correctly did with the parse method of the DateFormat class) but then you turn around and want to convert that java.util.Date to a String so you can put it into a List, so why not just put the original String into your List? Is it because you want to change the format? Fair enough, then you can use two DateFormat implementations, one to parse the incoming String to a Date, then the other to format the Date to the format you want. Or is it so you can do the sort chronologically? If that's the case, then you can write up a Comparator to do that, or you can store Dates in your list, sort them, and when it comes time to display this thing (if you ever do that) use a DateFormat implementation to convert those to a formatted String.
    Make sense?

  • DateFormat.parse

    Hi all,
    I am trying to parse some Strings into date objects, but i'm getting some strange output.
    The dates (Strings) that go into my program are:
    2005/3/08 09:12:38
    2005/3/10 17:29:57
    2005/3/11 15:39:59
    2005/3/23 13:30:03
    2005/3/23 13:32:49
    my code should take these strings, parse them into dates, add them to a List and sort the list. But the output i get is:
    Mon Aug 26 09:12:00 BST 2013
    Wed Aug 26 17:29:00 BST 2015
    Thu Aug 25 15:39:00 BST 2016
    Fri Aug 25 13:30:00 BST 2028
    Fri Aug 25 13:32:00 BST 2028
    as u can see - these are not the strings i entered originally. the code i am using is:
    public java.util.Date dateConverter(String dateString) throws Exception
    {     int intMonth = 99;
         String [] months = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
              String month = dateString.substring(4,7);
         for (int i = 0 ; i < 12 ; i++)
         {     if (months[i].equals(month))
              {     intMonth = i+1;
         dateString = dateString.substring(24,28) + "/" + intMonth + "/" + dateString.substring(8,10) + " " + dateString.substring(10,20);
         java.util.Date newDate = dateFormat.parse(dateString);
         return newDate;
    can anyone tell me whats missing from my code, and how i can get the correct output.
    thanks

    What happens if you do this? dateString = dateString.substring(24,28) + "/" + intMonth + "/" + dateString.substring(8,10) + " " + dateString.substring(10,20);
    java.util.Date newDate =dateFormat.parse(dateString);
    System.out.println("Parsing string " + dateString + " into date " + newDate);

  • Parse a Date to String

    Hi
    i would use this to parse String to Date :
    public Date parseFromString(String dateString){
          try {
              java.text.SimpleDateFormat formatter
                  = new java.text.SimpleDateFormat("dd/MM/yy");
              return formatter.parse(dateString);
          catch (Exception e) {
          return null;
      }how can i parse a Date to string?
    Thanks
    D

    check the API Docs for SimpleDateFormat - particularly the format method. public StringFormatFromDate(Date date){
          try {
              java.text.SimpleDateFormat formatter
                  = new java.text.SimpleDateFormat("dd/MM/yy");
              return formatter.format(date);
          catch (Exception e) {
               // You really shouldn't catch Exception - and you really should do something in your catch
               // blocks so you don't post a question like "my code executes no problem, but nothing happens...
               e.printStackTrace();
          return null;
      }

  • Improving my date parsing

    Hi, I have two methods that I use together to parse dates from raw text files:
    I format the date with this:
    public static String formatDate(String date){
              String[] parts = null;
              String yr = "";
              String mn = "";
              String dy = "";
              String pad = "0";
              if(date.contains("/")){
                   parts = date.split("/");
                   if(parts.length==3){
                        if(parts[0].length()==4){
                             yr = parts[0];
                             mn = parts[1];
                             dy = parts[2];
                        }else if(parts[2].length()==4){
                             yr = parts[2];
                             mn = parts[0];
                             dy = parts[1];
              }else if(date.contains("-")){
                   parts = date.split("-");
                   if(parts.length==3){
                        if(parts[0].length()==4){
                             yr = parts[0];
                             mn = parts[1];
                             dy = parts[2];
                        }else if(parts[2].length()==4){
                             yr = parts[2];
                             mn = parts[0];
                             dy = parts[1];
              if(dy.length()==1){
                   dy = pad+dy;
              if(mn.length()==1){
                   mn = pad+mn;
              return yr+mn+dy;
         }Then I parse the formatted date with this:
    public static synchronized Date asOfDate(String str) {
              //System.out.println("here it is"+str);
              Date dd = null;
              Date ddd = null;
              if(str.contains("/")){
                   SimpleDateFormat sdf2 = new SimpleDateFormat("MMddyyyy");
              str = str.replace("/", "");
              String yr = str.substring(0, 4);
              String mn = str.substring(4, 6);
              String d = str.substring(6, 8);
              System.out.println(yr);
              System.out.println(mn);
              System.out.println(d);
              String dddd = mn+ d + yr;
              //System.out.println(dddd);
              try {
                   dd = sdf2.parse(dddd);
              } catch (ParseException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              }else{
                   SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
                   try {
                        dd= sdf2.parse(str);
                   } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              return dd;
         }My question is even if I try to prevent the exceptions by checking the String length before formatting, I still keep getting Exceptions. Im just trying to only run these two methods of the String looks good. What am I doing wrong?
    I try to do this:
    if((string.length()==8))
    string date = TradeHelper.formatDate(temp.substring(84, 92);
    //then
    TradeHelper.asOfDate(date);Im trying for this:
    If the date ="", don't try anything.
    but this doesn't seem to work.
    java.text.ParseException: Unparseable date: ""
         at java.text.DateFormat.parse(DateFormat.java:335)
         at helper.TradeHelper.asOfDate(TradeHelper.java:213)
         at dazl.DAZLClass.parseFile(DAZLClass.java:127)
         at dazl.DAZLClass.main(DAZLClass.java:48)I know this is stupid, but I'm a little buried right now and could use the extra eyes.

    How about sometime like the following to parse dates with / in them. You don't have to remove them first.
    public static Date asOfDate(String dateStr) {
      String format;
      switch(dateStr.indexOf('/')) {
        case 4: format = "yyyy/MM/dd"; break;
        case 2: format = "MM/dd/yyyy"; break;
        default: throw new IllegalArgumentException("Unknown format for "+dateStr);
      SimpleDateFormat sdf = new SimpleDateFormat(format);
      return sdf.parse(dateStr);
    }

  • Parsing the Time

    Hello everyone
    Iam trying to parse a string to a SimpleDateFormat and then again to simply display the time. The incoming date is in the format "yyyyMMddHHmmss", the first section of the code <string2Date> converts the string into an eligible standard java date format and this works fine, the second half <string2Time> I'm having a bit of problem with. I wanted to parse the date further and display the time only "HHmmss", the obstacles I've come across is
    HHmmss is not the same length and form as the input yyyyMMddHHmmss
    Casting a Date to a String
    Can anyone help? Please note I'm using jdk1.1
    import java.text.*;
    import java.util.*;
    import java.text.DateFormat;
    import java.io.*;
    import java.lang.Integer;
    public class TimeConvertor extends SimpleDateFormat
              protected Date theDate;     
              protected Date d;
              protected Date theTime;
    public Date string2date(String DateString){     
              String tf="yyyyMMddHHmmss";
              SimpleDateFormat df = new SimpleDateFormat (tf);
              try{
              theDate=df.parse(DateString);
              catch (Exception ex) {
              System.out.println("error in time conv");
         return theDate;
    public Date string2time (String DateString){
              DateFormat tf = new SimpleDateFormat ("yyyyMMddHHmmss");
              DateFormat tdf = new SimpleDateFormat ("hh:mm:ss");
              try
                   d = tf.parse (DateString);
         /*<theTime> wants to parse a string and it wants it the same length as <tf>
         *so this line <df> is an attempt to convert <d> into a string and look only
         at the time of the string/
                   String df=(String)toString(d(Integer.parseInt.substring(8,14)));
                   theTime = tdf.parse (df);
              catch (ParseException e)
                   System.out.println ("Problem parsing hour value");
                   System.out.println (e);
                   e.printStackTrace ();
              System.out.println ("Output = " + theTime);
              return theTime;
    }

    Thanks I followed your advice... i'm getting closer- it compiles and runs but it has a "-depreciator" warning. I wanted to plot a graph: measurements versus time. Having the option of displaying day, week or month plot. The day plot would just display the times associated with that day, then a week with date+time etc. I'd still want the time associated with the date, parsing would be purely for display purposes. Using the Calendar is the best solution, Thanks! My last questions {see comments on code below} are why am i getting this "-dep" warning & can i get rid of it; also how can i display hour:minutes:seconds with out getting the error ")"?
    Thanks again
    import java.text.*;
    import java.util.*;
    import java.text.DateFormat;
    import java.io.*;
    import java.lang.Integer;
    import java.lang.String;
    public class TimeConvertor extends SimpleDateFormat
              protected Date theDate;     
              protected Date d;
              protected Date theTime;
              String tf="yyyyMMddHHmmss";
              SimpleDateFormat df = new SimpleDateFormat (tf);
             Calendar c = Calendar.getInstance();
    public Date string2date(String DateString){     
              try{
                   theDate=df.parse(DateString);
              catch (Exception ex) {
                    System.out.println("error in time conv");
               return theDate;
    public Date string2time (Date theDate){
                      c.setTime(theDate);
                      /*theDate.getMinutes(),theDate.getHours(),etc causes the -dep warning*/   
                  c.set(Calendar.HOUR, theDate.getHours());
                  c.set(Calendar.MINUTE,theDate.getMinutes());  
                  c.set(Calendar.SECOND,theDate.getSeconds());
        /*Error ')' expected*/          
         System.out.println("Time = " c.get(Calendar.HOUR)":" c.get(Calendar.MINUTE) ":" c.get(Calendar.SECOND)); 
         /* This works fine prints out the right hour, minutes, sec but Individually i wanted HH:mm:ss*/     
         System.out.println(c.get(Calendar.HOUR));
         System.out.println(c.get(Calendar.MINUTE));
         System.out.println(+c.get(Calendar.SECOND));
         return c.getTime();
    }

  • Parse Exception, Expert please help!

    Hello World,
    Please have a look at following code snippet.
    String dateString (Getting from client)
    SimpleDateFormat defaultformat = new SimpleDateFormat();
    Date d = null;
    try {
    d = defaultformat.parse(dateString);
    catch(ParseException pe)
    System.out.println(pe.getMessage());
    In this program I require date object for further processing. I get dateString (date and time) from client. I got Date object from above code for all locales except Chinese. When Chinese client enter a date, the string I got contains some Chinese characters (representing AM. and PM.) And I get ParseException. Now my question is why parse function is throwing exception? I have Chinese font on machine also. I am using Jdk1.4.2 and operating system is Windows XP.
    Can anybody tell me solution on this?
    Thanks and Regards,
    Sachin Dare.

    Probably your locale is not China. I think you can either pass a Locale to a SimpleDateFormat constructor, or maybe there's a setLocale method. Check SimpleDateFormat's docs for handling locales.

  • SimpleDateFormat parses wrong date successfully (lenient = false). Why?

    Hi
    I've got a problem validating date by SimpleDateFormat. Format "yyyy" successfully parses string like "2009-78" into date 01.01.2009. Can you please help me with it?
    Here is my code:
    SimpleDateFormat format = new SimpleDateFormat("yyyy");
    format.setLenient(false);
    String dateStr = "2009-78";
    Date date;
    try {
        date = format.parse(dateStr);
    } catch (ParseException e) {
        date = null;
        e.printStackTrace();
    System.out.println(String.format("String '%s' parsed to date %s", dateStr, date));Output:
    String '2009-78' parsed to date Thu Jan 01 00:00:00 MSK 2009I need an exception to be thrown in such situation. How can I check where the string represents a correct date?
    Thanks for your help.
    Evgeny
    Edited by: su.eug on Apr 13, 2009 12:56 AM

    Read the comments in the API:
    [http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html#parse(java.lang.String)|http://java.sun.com/javase/6/docs/api/java/text/DateFormat.html#parse(java.lang.String)]
    You could try the other overload of parse, if you want to test whether the whole String was used:
    [http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String, java.text.ParsePosition)|http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String,%20java.text.ParsePosition)]
    (Sorry--the second link doesn't go to the right place. There is a version of "parse" with two parameters, which you can use to determine if the whole String was used.)

  • How to parse this textfile

    I have a plan textfiel that i'm able to read but i can't parse the date and numbers in the text file.
    text content: [ 2007.10.19 11:53:42 ] (test) <color=0xffbbbb00>Your item, costs 598.0 euro.
    i suppose i can use substring/tokenizer but my knowledge in the tokenizer is limited.
    Does anyone know how to parse the date and costs so i can show the total costs for an item?

    mkoryak wrote:
    import java.util.regex.*;
    holy regex, batman! I definitely have to devote more time to regex. My mere mortal solution to some of the extractions went along these lines:
        private Color getColor(String text)
            Color c = null;
            String[] strArr = text.split("[<>]"); 
            // the forum mangles this  :( 
            // it should have angle brackets inside of square brackets. 
            String colorStr = strArr[1];
            colorStr = colorStr.substring(colorStr.indexOf("=") + 3);
            int[] colorInts = new int[4];
            for (int i = 0; i < colorInts.length; i++)
                String colorSubStr = colorStr.substring(2 * i, 2 * i + 2);
                colorInts[i] = Integer.parseInt(colorSubStr, 16);
            c = new Color(colorInts[0], colorInts[1], colorInts[2], colorInts[3]);
            return c;
        private Date getDate(String text)
            Date d = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
            String[] dateStrArr = text.split("[\\[\\]]");
            String dateStr = dateStrArr[1].trim();
            try
                    d = sdf.parse(dateStr);
            catch (ParseException e)
                e.printStackTrace();
            return d;
        }I will definitely study your code mkoryak, thanks.
    Edited by: petes1234 on Oct 24, 2007 10:09 AM

  • 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 parsing difficulty

    Hello all,
    Recently, I had to parse Strings into Dates using SimpleDateFormat. The difficulty I had was because the Strings had timezone offsets. The code below shows the 3 tests it took to create a Date object of specified TimeZone.
    Test 1
    Fails because I don't set the TimeZone for SimpleDateFormat.
    Test 2
    Works for the first String because the TimeZone matches the timezone in the String.
    Test 3
    Works for all Strings, but is cumbersome because I have to parse the end of the String myself.
    My question is this: Shouldn't SimpleDateFormat parse a String directly into a Date without having you to specify the TimeZone of that Date? This problem was very annoying to solve and goes against logic (at least mine!).
    I'm interested in any thoughts on this matter. Am I being unreasonable, or is this poorly explained in the API?
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.SimpleTimeZone;
    public class DateTests {
         private static String DATE_FORMAT = "yyyyMMddHHmmss.SSSZ";
         private static String[] TEST_DATA = {
              "20020125120434.175+0800",
              "20031101195801.942+0000",
              "20041231000159.999-0536",
              "20050220165427.531-1100"
         private static int MINUTE = 60 * 1000; //in milliseconds
         private static int HOUR = 60 * MINUTE;
         public static void main(String[] args) {
              test1();
              test2();
              test3();
         private static void test1() {
              System.out.println("**** TEST 1 ****\n");
              DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
              formatter.setLenient(false); //want to check that dates are valid
              for (String dateString : TEST_DATA) {
                   try {
                        Date date = formatter.parse(dateString);
                        System.out.println("Success! The date is: "+date.toString());
                   } catch (ParseException e) {
                        System.out.println(dateString + " has error index of: " + e.getErrorOffset());
              //out of curiousity, lets see the String representation of the current date & time
              Date now = new Date();
              String currentDate = formatter.format(now);
              System.out.println("\nThe current date as a String: "+currentDate);
              System.out.println("\n");
         private static void test2() {
              System.out.println("**** TEST 2 ****\n");
              DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
              formatter.setLenient(false); //want to check that dates are valid
              //lets make the timezone +0800
              formatter.setTimeZone(new SimpleTimeZone(8 * HOUR, "GMT")); //8 hour offset
              for (String dateString : TEST_DATA) {
                   try {
                        Date date = formatter.parse(dateString);
                        System.out.println("Success! The date is: "+date.toString());
                   } catch (ParseException e) {
                        System.out.println(dateString + " has error index of: " + e.getErrorOffset());
              System.out.println("\nSuccess for the first date. Why? The timezone of the formatter matches the date.");
              System.out.println("\n");
         private static void test3() {
              System.out.println("**** TEST 3 ****\n");
              DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
              formatter.setLenient(false); //want to check that dates are valid
              for (String dateString : TEST_DATA) {
                   try {
                        //lets set a timezone for each individual date
                        int length = dateString.length();
                        int gmtMinutes = Integer.parseInt(dateString.substring(length-2, length));
                        int gmtHours = Integer.parseInt(dateString.substring(length-4, length-2));
                        int timeZone = gmtMinutes * MINUTE + gmtHours * HOUR;
                        timeZone = dateString.charAt(length-5) == '+' ? timeZone : -timeZone;
                        formatter.setTimeZone(new SimpleTimeZone(timeZone, "GMT"));
                        Date date = formatter.parse(dateString);
                        System.out.println("Success! The date is: "+date.toString());
                   } catch (ParseException e) {
                        System.out.println(dateString + " has error index of: " + e.getErrorOffset());
    }-Muel

    Date objects don't have time zones.
    This is true, my problem was that I needed to parse both the Date and the TimeZone from a String. I got misled by the SimpleDateFormat documentation (the symbol Z), and somehow got the impression that a Date should have an associated TimeZone!
    In hindsight, it is clear that Z should be used for Date strings containing a timezone and that SimpleDateFormat uses the timezone to modify the Date so that it's correct for the timezone of the current machine. If that makes sense!
    -Muel

Maybe you are looking for

  • Excel 2008, read-only file access from network volume

    Hi, Need some assistance please. I recently setup a Macbook Pro 17" 2.4Ghz (10.5.2) and did a migration from a Powerbook G4. Installed Office 2008. Excel will not open ANY files from a network volume without giving a read-only access error. Word is o

  • Third Party order which was closed is appearing in Customer open credit

    Hi, We had earlier closed the status for a partially Invoiced Third party Sales order ,where Goods Receipt quantity was more than the PO and Customer Sales order quantity from Being Processed to completed through a Z transaction. The payments for all

  • Why do I have to DL an app twice?

    I bought an app about the 50th anniversary of JFK's assassination from NBC and it's on the iPad and it's working just fine. However, when I plug the iPad into the computer to sync various things, it wants to download that app again. Only problem is t

  • Importing videos to iMovie issue

    Recently, when I import videos from my SD card, from my camera, to iMovie on my MacBook Pro (Mac OS X Lion 10.7.5), the videos that show up don't have the sound waves on the bottom but they still have audible sound. However, it makes editing this vid

  • Af:table fetching next range of data

    Hi! I have a table component on jsf page, property RangeSize set to 25(default). Now I want to invoke a method from my managed bean each time when is fetching next range of data of ViewObject(next 25 rows). But how can I invoke this method? Does anyb