从日期字符串中提取时间

JJu*_*ior 49 java string time date

如何格式化"2010-07-14 09:00:02"日期字符串以进行描述"9:00"

Bal*_*usC 111

用于SimpleDateFormat在日期字符串和真实Date对象之间进行转换.以a Date作为起点,您可以根据javadoc中定义的各种模式轻松应用格式SimpleDateFormat(单击Javadoc的蓝色代码链接).

这是一个启动示例:

String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
Run Code Online (Sandbox Code Playgroud)


Ada*_*dam 14

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);
Run Code Online (Sandbox Code Playgroud)

http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html


Pet*_*lák 11

一个非常简单的方法是使用Formatter(请参阅日期时间转换),或者更直接地String.format

String.format("%tR", new Date())
Run Code Online (Sandbox Code Playgroud)


Ole*_*.V. 5

当这个问题被问到时,其他答案都是很好的答案。时间在流逝,DateSimpleDateFormat更新更好的类取代并不再使用。2017年,使用包中的类java.time

    String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
            .format(DateTimeFormatter.ofPattern("H:mm"));
Run Code Online (Sandbox Code Playgroud)

结果就是想要的,9:00