applyPattern() in SimpleDateFormat gives NullPointerEcxeption with white space in java -
i have code formats date pattern dd-mm-yyyy:
simpledateformat sdf = new simpledateformat("yyyy-mm-dd't'hh:mm:ss.s"); sdf.applypattern("yyyy-mm-dd"); date date_out = null; try { date_out = sdf.parse(date); } catch (parseexception e) { // todo auto-generated catch block e.printstacktrace(); } sdf.format(date_out);
however when change separator "-" white space or slash "/" nullpointerecxeption on format() line. simpledateformat accept white space or other character date separators?
the issue sdf.parse(date);
null if date
not match pattern. if change pattern of simpledateformat object don't change format of date parsing parseexception thrown , date_out
null. sdf.format()
throw nullpointerexception when try format null string.
based on comment think bit more explanation required examples - i'm editing answer appropriately...
simpledateformat applypattern changes pattern of simpledateformat object acts in same way string in constructor does, is, tells formatter pattern expect / use output.
for think want, need 2 simpledateformatters, input 1 , output one. eg.
simpledateformat sdfinput = new simpledateformat("yyyy-mm-dd't'hh:mm:ss.s"); simpledateformat sdfoutput = new simpledateformat(yyyy mm dd"); date date_out = null; try { date_out = sdfinput.parse(date); } catch (parseexception e) { // todo auto-generated catch block e.printstacktrace(); } string myoutputteddate = sdfoutput.format(date_out);
having said guess put applypattern after parsing, , before output so...
simpledateformat sdf = new simpledateformat("yyyy-mm-dd't'hh:mm:ss.s"); string reformatteddate = ""; date date_out = null; try { date_out = sdf.parse(date); } catch (parseexception e) { // todo auto-generated catch block e.printstacktrace(); } sdf.applypattern("yyyy mm dd"); if (date_out != null) { reformatteddate = sdf.format(date_out); }
hope helps bit more.
Comments
Post a Comment