如何从字符串中仅获取日期月份和时间

时间:2015-03-24 07:23:44

标签: java

我从数据库" 2015-03-17 15:27:38"

获得以下字符串

从此我想只显示

03-17 15:27  (Month - Date and Time with minutes and seconds)

我正在尝试以下方式

import java.util.Random;

public class Test {
    public static void main(String args[]) throws JSONException {
        String created = "2015-03-17 15:27:38";
        if (created != null && !created.isEmpty() && created.length() >= 19) {
            created = created.substring(0, created.length() - 5);
        }
        System.out.println(created);
    }
}

你能告诉我怎么做吗?

2 个答案:

答案 0 :(得分:2)

使用SimpleDateFormatString值解析为Date,然后使用其他SimpleDateFormat按照您的方式格式化值

try {
    String created = "2015-03-17 15:27:38";
    SimpleDateFormat in = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = in.parse(created);

    SimpleDateFormat out = new SimpleDateFormat("MM-dd HH:mm");
    System.out.println(out.format(date));
} catch (ParseException ex) {
    Logger.getLogger(JavaApplication979.class.getName()).log(Level.SEVERE, null, ex);
}

输出03-17 15:27

答案 1 :(得分:2)

除非您能保证日期格式永远不会改变,否则您不应该开始创建自己的字符串解析代码。

Java为您提供各种内置"用于处理数字和日期的API;例如https://docs.oracle.com/javase/tutorial/datetime/

相关问题