在Java中将字符串日期格式化为其他格式

gam*_*ofe 0 java string android date date-format

我正在尝试格式化具有date以下格式的键的JSON :

日期:“ 2017-05-23T06:25:50”

我当前的尝试如下:

private String formatDate(String date) {
  SimpleDateFormat format = new SimpleDateFormat("MM/DD/yyyy");
  String formattedDate = "";

  try {
    formattedDate = format.format(format.parse(String.valueOf(date)));
  } catch (ParseException e) {
    e.printStackTrace();
  }

  return formattedDate;
}
Run Code Online (Sandbox Code Playgroud)

但是在这种情况下,结果不会显示在我的应用中,它TextView是不可见的,并且我无法记录任何内容。

我确实尝试过其他解决方案,但对我而言没有成功。我不知道是否是因为传入的值是一个字符串。

Ram*_*mbu 5

使用此代码格式化您的`2017-05-23T06:25:50'

String strDate = "2017-05-23T06:25:50";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date convertedDate = new Date();
try {
    convertedDate = dateFormat.parse(strDate);
    SimpleDateFormat sdfnewformat = new SimpleDateFormat("MMM dd yyyy");
    String finalDateString = sdfnewformat.format(convertedDate);
} catch (ParseException e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

转换后的finalDateString设置为您的textView

  • 勿乱阅读[SimpleDateFormat](https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html)。 (2认同)