Java函数实现时间戳的格式化
时间戳是指从某一固定的起始时间(如1970年1月1日00:00:00)到某个时间点所经过的秒数。在Java中,获取当前时间的代码如下:
System.currentTimeMillis();
该方法返回的是当前时间的毫秒数,而不是秒数。因此在使用时需要除以1000,将毫秒数转换为秒数。时间戳通常以整数的形式表示,无法直观地体现时间的信息,因此需要将时间戳格式化为可读性更高的日期时间字符串。
Java中提供了多种方式来格式化时间戳,下面列举了几种常见的方式:
1. SimpleDateFormat类
SimpleDateFormat是Java中的一个日期时间格式化类,可以将日期时间转换为指定格式的字符串,也可以将字符串转换为日期时间。
public String formatTimestamp(long timestamp, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(new Date(timestamp * 1000));
}
// 示例
System.out.println(formatTimestamp(System.currentTimeMillis() / 1000, "yyyy-MM-dd HH:mm:ss"));
其中,第一个参数是时间戳,第二个参数是格式化的模板,常见的模板有以下几种:
- "yyyy-MM-dd": 年月日
- "yyyy-MM-dd HH:mm:ss": 年月日时分秒
- "HH:mm:ss": 时分秒
- "yyyyMMddHHmmss": 年月日时分秒(无符号)
2. DateTimeFormatter类
Java 8中新增了一个日期时间格式化类DateTimeFormatter,可以使用该类来格式化日期时间,支持线程安全。
public String formatTimestamp(long timestamp, String pattern) {
LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
return DateTimeFormatter.ofPattern(pattern).format(dateTime);
}
// 示例
System.out.println(formatTimestamp(System.currentTimeMillis() / 1000, "yyyy-MM-dd HH:mm:ss"));
DateTimeFormatter使用ISO格式用法,使用常量来代表格式,例如:
- DateTimeFormatter.ISO_LOCAL_DATE:年月日
- DateTimeFormatter.ISO_LOCAL_TIME:时分秒
- DateTimeFormatter.ISO_LOCAL_DATE_TIME:年月日时分秒
也可以自定义格式模板,例如:"yyyy-MM-dd HH:mm:ss"。
3. String.format()方法
String.format()方法可以通过格式字符串来实现日期时间格式化。
public String formatTimestamp(long timestamp, String pattern) {
Date date = new Date(timestamp * 1000);
return String.format(pattern,
date.getYear() + 1900,
date.getMonth() + 1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds());
}
// 示例
System.out.println(formatTimestamp(System.currentTimeMillis() / 1000, "%04d-%02d-%02d %02d:%02d:%02d"));
其中,第一个参数是格式化字符串,每个格式化项都对应一个时间字段,常见的格式化项有以下几种:
- "%d": 十进制整数
- "%02d": 十进制整数,不足两位时前面补0
- "%04d": 十进制整数,不足四位时前面补0
综上,Java提供了多种方式来格式化时间戳,可以根据实际需求选择相应的方式。
