java时间格式转换
时间: 2023-11-18 09:57:15 浏览: 108
Java时间格式转化
Java中有多种方法可以进行时间格式转换,以下是其中的一些方法:
1. 获取当前时间:
```java
Date date = new Date();
```
2. 获取当前时间戳:
```java
long timestamp = System.currentTimeMillis();
```
3. 日期转时间戳:
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2021-01-01 00:00:00");
long timestamp = date.getTime();
```
4. 时间戳转日期:
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long timestamp = 1609459200000L;
Date date = new Date(timestamp);
String dateStr = sdf.format(date);
```
5. 日期转字符串:
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String dateStr = sdf.format(date);
```
6. 字符串转日期:
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = "2021-01-01 00:00:00";
Date date = sdf.parse(dateStr);
```
7. CST格式转日期:
```java
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
String dateStr = "Fri Jan 01 00:00:00 CST 2021";
Date date = sdf.parse(dateStr);
```
8. 非标准格式转日期:
```java
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String dateStr = "20210101000000";
Date date = sdf.parse(dateStr);
```
9. 日期字符串格式转换:
```java
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
String dateStr1 = "2021-01-01 00:00:00";
Date date = sdf1.parse(dateStr1);
String dateStr2 = sdf2.format(date);
```
10. 日期转日历:
```java
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
```
11. 日历转日期:
```java
Calendar calendar = Calendar.getInstance();
calendar.set(2021, 0, 1, 0, 0, 0);
Date date = calendar.getTime();
```
12. 日期计算:
```java
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.DAY_OF_MONTH, 1); // 加一天
Date date = calendar.getTime();
```
13. 计算日期间隔的方法总结:
Java中有多种方法可以计算日期间隔,例如使用Calendar类的getTimeInMillis()方法计算时间戳差值,或者使用Joda-Time库进行日期计算等。
阅读全文