将String及时转换为没有Date的Time对象

sya*_*kah 9 java time date

我有问题将String时间转换为Time对象,因为它与Date一起打印.这是我的代码.

String time = "15:30:18";

DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(time);

System.out.println("Time: " + date);
Run Code Online (Sandbox Code Playgroud)

如何转换和打印时间只有没有日期在java中.如果你能举一个例子会更好.

谢谢.

ska*_*man 25

使用与SimpleDateFormat解析它时相同的内容:

String time = "15:30:18";

DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(time);

System.out.println("Time: " + sdf.format(date));
Run Code Online (Sandbox Code Playgroud)

请记住,Date对象始终表示组合的日期/时间值.它无法正确表示仅限日期或仅限时间的值,因此您必须使用正确的值DateFormat以确保只"看到"所需的部件.


小智 9

这也有效

String t = "00:00:00" 
Time.valueOf(t);
Run Code Online (Sandbox Code Playgroud)


Bas*_*que 5

Joda-Time | java.time

如果要使用没有日期和时区的仅时间值,则必须使用Joda-Time库或Java 8中捆绑的新java.time包(受Joda-Time启发)。

这两个框架都提供了一个LocalTime类。

在Joda-Time 2.4中…

LocalTime localTime = new LocalTime( "15:30:18" );
Run Code Online (Sandbox Code Playgroud)

在java.time中...

LocalTime localTime = LocalTime.parse( "15:30:18" );
Run Code Online (Sandbox Code Playgroud)