简体   繁体   中英

how to change date format in java?

i am getting my date input as a string in the format dd-mm-yy through jsp page. Because this format is better to understand . But now i want to store the date in yyyy-MM-dd HH:mm:ss format in my database. I am using the following code.

try
    {       
    String s="30-04-2013";
    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    d1=new SimpleDateFormat("yyyy-MM-dd").parse(s);
    System.out.println(d1);
    System.out.println(ft.format(d1));
    } catch(Exception e) {
        System.out.println("Exception:"+e);
    }

My Jsp date format is dd-mm-yy , but it gives answer as

Tue Oct 04 00:00:00 IST 35
0035-10-04 00:00:00

what is my mistake? can tell me anyone please

Thank you.

d1=new SimpleDateFormat("yyyy-MM-dd").parse(s);

should be

d1=new SimpleDateFormat("dd-MM-yyyy").parse(s);

because the input date String you've provided String s="30-04-2013"; is of the format, dd-MM-yyyy . Hence, to parse this, you need to give dd-MM-yyyy format in your SDF.

Change the format in your code from yyyy-MM-dd to dd-MM-yyyy . A simple debug would have solved this issue.

See below the working program. See the parse and format method.

import java.text.SimpleDateFormat;
public class DateParsing {

    public static void main(String args[]) {

        String s = "30-04-2013";
        SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy");
        SimpleDateFormat nt = new SimpleDateFormat("yyyy-MM-dd");
        try {
            System.out.println(nt.format(ft.parse(s)));
        }

        catch (Exception e) {
            System.out.println("Exception:" + e);
        }
    }

}

i think you need to pass the Date object to format() method of SimpleDateFormat class instead of passing string to it

just try to do like as follows

SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatted_date = ft.format(new Date());
System.out.println(formatted_date);

let me know the status

happy coding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM