Calendar转换为String
时间: 2024-05-05 11:20:32 浏览: 9
将一个Calendar对象转换为String对象可以使用SimpleDateFormat类,如下所示:
```
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(calendar.getTime());
```
这里我们获取当前时间的Calendar对象,然后使用SimpleDateFormat类将其格式化为指定的字符串格式。你可以修改代码中的格式字符串以满足你的需求。
相关问题
Java String转换Calendar
Java中可以使用SimpleDateFormat类将字符串转换为Calendar对象。具体步骤如下:
1. 创建SimpleDateFormat对象,设置日期时间格式。
2. 调用SimpleDateFormat的parse方法将字符串解析为Date对象。
3. 创建Calendar对象,将Date对象设置到Calendar中。
示例代码如下:
```
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class StringToCalendarExample {
public static void main(String[] args) throws Exception {
String dateString = "2022-05-01 08:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(dateString);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println(calendar.getTime());
}
}
```
上面的代码中,首先创建一个SimpleDateFormat对象,设置日期时间格式为"yyyy-MM-dd HH:mm:ss"。然后调用SimpleDateFormat的parse方法将字符串"2022-05-01 08:00:00"解析为Date对象。接着创建一个Calendar对象,并将前面解析得到的Date对象设置到Calendar中。最后输出Calendar对象表示的时间。
Calendar转String
可以使用SimpleDateFormat类将Calendar对象转换为String类型,以下是示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class CalendarToString {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(calendar.getTime());
System.out.println("Calendar转换后的字符串为:" + strDate);
}
}
```
首先获取当前时间的Calendar实例,然后创建SimpleDateFormat对象,指定日期格式,最后使用format方法将Calendar对象转换为String类型。
相关推荐
![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)