Change the format of Date Java [closed]

2020-01-27 07:14发布

I've the Date object with the format

 /107/2013 12:00:00 AM

Expected value for me:

2013-07-01

How I do this?.

I'm trying with this code

public static  Date  formatearFecha( Date fecha ){

    String fechaString = new SimpleDateFormat("yyyy-MM-dd").format(fecha) ;
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date fechaFormateada = null;
    try {
        fechaFormateada = df.parse(fechaString);
    } catch (ParseException ex) {
        Logger.getLogger(TestThings.class.getName()).log(Level.SEVERE, null, ex);
    }
    return fechaFormateada;

}

When I try to make a test I get this:

 System.out.println( formatearFecha(myDate) );
 Mon Sep 30 00:00:00 COT 2013

Update:

my problem was in sql change to java.util.Date to java.sql.Date
I solve this so:

private  String formatearFecha( Date fecha ){
    return new SimpleDateFormat("yyyy-MM-dd").format(fecha);
}

private java.sql.Date stringToSQLDate( String fecString ){

    java.sql.Date fecFormatoDate = null;
    try {
          SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd", new Locale("es", "ES"));
         return  new java.sql.Date(sdf.parse(fecString).getTime());
    } catch (ParseException ex) { }
    return null;
}

And test:

stringToSQLDate( formatearFecha( myDate ) );

标签: java date
2条回答
够拽才男人
2楼-- · 2020-01-27 08:01
Date myDate = .......
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dateFormat.format(myDate));
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-01-27 08:05

First of all: java.util.Date object never has a format stored in it. You can think of Date as an object containing long value of milliseconds since epoch at UTC timezone. The class has few methods, but no timezone offset, formatted pattern etc stored in it.

Secondly, following basic code can be used to format a date to yyyy-MM-dd in your machine's locale:

Date mydate = ...
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String mydateStr = df.format(mydate);

Similarly, you can parse a string "/107/2013 12:00:00 AM" into a date object in your machine's locale like this:

String mydateStr = "/107/2013 12:00:00 AM";
DateFormat df = new SimpleDateFormat("/dMM/yyyy HH:mm:ss aa");
Date mydate = df.parse(mydateStr);

Two method above can be used to change a formatted date string from one into the other.

See the javadoc for SimpleDateFormat for more info about formatting codes.

查看更多
登录 后发表回答