如何将日期转换为yyyy-MM-dd格式?

Use*_*343 30 java date simpledateformat date-formatting

2012年12月1日00:00:00 GMT

我必须将上述日期转换为以下格式

2012年12月1日

我怎么能够?

我试过以下方法,但它没有工作

public Date ConvertDate(Date date){

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    String s = df.format(date);
    String result = s;
    try {
        date=df.parse(result);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return date;
  }
Run Code Online (Sandbox Code Playgroud)

Nid*_*nan 67

用这个.

java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);
Run Code Online (Sandbox Code Playgroud)

你会得到输出

2012-12-01
Run Code Online (Sandbox Code Playgroud)

  • @vels4j 为什么不分享使用 Calendar 来替换已弃用的 Date 构造函数的代码? (2认同)