Unexpected Output while trying yo convert String to date using FastDateFormat

百般思念 提交于 2019-12-25 18:55:10

问题


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

回答1:


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?



来源:https://stackoverflow.com/questions/43518495/unexpected-output-while-trying-yo-convert-string-to-date-using-fastdateformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!