帮我通java写一个时间工具类
时间: 2023-05-19 14:04:36 浏览: 113
好的,以下是一个简单的 Java 时间工具类的代码:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeUtils {
// 获取当前时间戳
public static long getCurrentTimestamp() {
return System.currentTimeMillis();
}
// 将时间戳转换为日期字符串
public static String timestampToDate(long timestamp, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = new Date(timestamp);
return sdf.format(date);
}
// 将日期字符串转换为时间戳
public static long dateToTimestamp(String dateStr, String format) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = sdf.parse(dateStr);
return date.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
// 获取当前日期字符串
public static String getCurrentDate(String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = new Date();
return sdf.format(date);
}
// 获取当前年份
public static int getCurrentYear() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.YEAR);
}
// 获取当前月份
public static int getCurrentMonth() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.MONTH) + 1;
}
// 获取当前日
public static int getCurrentDay() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.DAY_OF_MONTH);
}
}
```
你可以根据自己的需要来使用这个工具类,比如获取当前时间戳、将时间戳转换为日期字符串、将日期字符串转换为时间戳、获取当前日期字符串、获取当前年份、获取当前月份、获取当前日等。
阅读全文
相关推荐


















