java string转时分
时间: 2023-07-04 10:24:16 浏览: 68
可以使用Java中的SimpleDateFormat类来将字符串转换为时分的形式。具体实现代码如下:
```java
String time = "12:34";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = sdf.parse(time);
long milliseconds = date.getTime();
int minutes = (int) (milliseconds / 1000 / 60);
int hours = minutes / 60;
minutes = minutes % 60;
System.out.println(String.format("%02d:%02d", hours, minutes));
```
这段代码将字符串"12:34"转换为时分的形式,输出结果为"12:34"。
相关问题
java string转时分秒
可以使用Java中的SimpleDateFormat类来将字符串转换为时分秒的形式。具体实现代码如下:
```java
String time = "12:34:56";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(time);
long milliseconds = date.getTime();
int seconds = (int) (milliseconds / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
int hours = minutes / 60;
minutes = minutes % 60;
System.out.println(String.format("%02d:%02d:%02d", hours, minutes, seconds));
```
这段代码将字符串"12:34:56"转换为时分秒的形式,输出结果为"12:34:56"。
java string时分秒转date
以下是Java中将字符串时分秒转换为Date的示例代码:
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateExample {
public static void main(String[] args) {
String strDate = "2021-10-01 12:30:45";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = formatter.parse(strDate);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们使用SimpleDateFormat类将字符串“2021-10-01 12:30:45”转换为Date对象。我们首先创建一个SimpleDateFormat对象,指定日期格式为“yyyy-MM-dd HH:mm:ss”,然后使用parse()方法将字符串转换为Date对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)