Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

java - Unexpected Output while trying yo convert String to date using FastDateFormat

Problem:

I need to pass Date class Object to a function and that Date Object should contain one Day ahead of the System Time. For Ex: If Today's Date is 2017-04-20 17:01:31.Then,Date Object should contain 2017-04-21 17:01:31

Is it possible to store a specified format into Date Class Object and pass into it.

I tried the following thing and it didn't work.

Can anyone guide me if it is possible through Code or should I use SQL Query Concept to add a Day.

Below is my Code

     public static void main(String[] args) throws ParseException {
        String dateFormat="yyyy-MM-dd HH:mm:ss";
            String s2=addDate(dateFormat);
            convertStringToDate(s2,dateFormat);

        }
    public static Date convertStringToDate(String dateInStr, String dateFormat) throws ParseException
    {
        FastDateFormat fdf=FastDateFormat.getInstance(dateFormat);//("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        date = fdf.parse(dateInStr);
        System.out.println("From convertStringToDate ");
        System.out.println(date);
        return date;
    }
public static String addDate(String dateFormat) throws ParseException{
            FastDateFormat fdf=FastDateFormat.getInstance(dateFormat);
            Calendar c = Calendar.getInstance();    
            c.add(Calendar.DATE,1);
            String s1=fdf.format(c.getTime());
            System.out.println("From addDate ");
            System.out.println(s1);
            return s1;
        }

Expected Output from convertStringToDate:

2017-04-21 17:01:31

OutputShown from convertStringToDate:

Fri Apr 21 17:01:31 IST 2017
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to obtain the instance of class Date. In your method addDate you get the required Date and then convert it to String and return a String. And then you convert your String back to Date Why don't you just return Date from your method addDate and be done with it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...