Sunday, 15 March 2015

Java Date object from String not working properly -



Java Date object from String not working properly -

i have run stubborn problem cannot seem solve. have looked solutions @ stackoverflow , have found lot of posts java date formatting, nil specific problem have.

basically, have situation need convert date strings java.util.date objects. using date , simpledateformat classes. dates encountering, works fine. dates, works changes actual date. 2 illustration dates :

fri feb 24 16:45:40 pst 2012 --> gets changed --> fri jan 06 16:45:40 pst 2012

wed jun 13 10:00:42 pdt 2012 --> gets changed --> wed jan 04 09:00:42 pst 2012

any thought why dates getting changed? way avoid or in different way? code copied below. can seek see talking about.

thanks in advance!

you can seek next jsp code:

<%@ page import="java.util.*" %> <%@ page import="java.net.*" %> <%@ page import="java.io.*" %> <%@ page import="java.text.*" %> <% string datestr = ""; date tmpdate = null; dateformat formatter = new simpledateformat("eee mmm dd hh:mm:ss z yyyy"); system.out.println("first test ---------------"); datestr = "fri feb 24 16:45:40 pst 2012"; tmpdate = (date) formatter.parse(datestr); system.out.println("original:"+datestr+":"); system.out.println("date obj:"+tmpdate.tostring()+":"); system.out.println("second test --------------"); datestr = "wed jun 13 10:00:42 pdt 2012"; tmpdate = (date) formatter.parse(datestr); system.out.println("original:"+datestr+":"); system.out.println("date obj:"+tmpdate.tostring()+":"); %>

i getting next output:

first test ------------ original:fri feb 24 16:45:40 pst 2012: date obj:fri jan 06 16:45:40 pst 2012: sec test ----------- original:wed jun 13 10:00:42 pdt 2012: date obj:wed jan 04 09:00:42 pst 2012:

use yyyy not yyyy in format string.

yyyy special thing, calendar week year.

see simpledateformat documentation more info.

java string date simpledateformat

No comments:

Post a Comment