2025-11-13 05:37:44Java获取时间&时间格式化最全总结

Java获取时间&时间格式化最全总结

最近遇到很多在Java里获取当前时间的问题,有的要求五花八门的,今天总结一下在Java中获取时间的方法和时间输出的格式化。

获取方式

java.util.Date

这个是我们最常用的,直接通过util包下得到当前时间通过SimpleDateFormat格式化后输出

//通过util下的Date包实现

Date date = new Date();

SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

System.out.println(dateFormat.format(date));

格式化的输出和不格式化的输出

显然不格式化的代码可读性不如格式化后的,在实际开发场景中更需要不同的格式化要求,讲完如何获取之后,后面会讲时间的各种格式化。

在java8中的新特性里提供了三种时间类LocalDate、LocalTime、LocalDateTime

*这三个都在java.time包下,后续标题省略包名

LocalDate

如果你只需要获取年月日,则用这个再好不过,

//获取当前年月日

LocalDate localDate = LocalDate.now();

System.out.println(localDate);

他的输出就是yyyy-mm-dd

你也可以通过构造方法构造指定的年月日

LocalDate localDate1 = LocalDate.of(2077, 7, 17);

三个参数已经提示的很清晰

当然,也可以用这个获取单个年月日、星期等

int year = localDate.getYear();

int year1 = localDate.get(ChronoField.YEAR);

Month month = localDate.getMonth();

int month1 = localDate.get(ChronoField.MONTH_OF_YEAR);

int day = localDate.getDayOfMonth();

int day1 = localDate.get(ChronoField.DAY_OF_MONTH);

DayOfWeek dayOfWeek = localDate.getDayOfWeek();

int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK);

月份和星期可以获得指定英文格式,如上。输出结果如下

LocalTime

如果只获取时分秒,那就用这个吧~

LocalTime localTime = LocalTime.now();

System.out.println(localTime);

这个也是一样,除了获取当前,也是可以指定附值

LocalTime localTime1 = LocalTime.of(13, 51, 10);

System.out.println(localTime1);

输出如下

获取范围更小的时分秒

//获取小时

int hour = localTime.getHour();

int hour1 = localTime.get(ChronoField.HOUR_OF_DAY);

//获取分

int minute = localTime.getMinute();

int minute1 = localTime.get(ChronoField.MINUTE_OF_HOUR);

//获取秒

int second = localTime.getSecond();

int second1 = localTime.get(ChronoField.SECOND_OF_MINUTE);

运行如下

LocalDateTime

如果你全都要,那自然是Date+Time=DateTime了

直接获取

LocalDateTime now = LocalDateTime.now();

System.out.println(now);

DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

System.out.println(now.format(formatter2));

指定时间

LocalDateTime localDateTime = LocalDateTime.now();

LocalDateTime localDateTime1 = LocalDateTime.of(2077, Month.SEPTEMBER, 7, 17, 17, 17);

LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime);

LocalDateTime localDateTime3 = localDate.atTime(localTime);

LocalDateTime localDateTime4 = localTime.atDate(localDate);

//这里的localTime和localDate拿的是上面定义的

Instant

拿秒

我们最熟悉的不过currentTimeMillis,在计算程序运行时间用的比较多,但在java.time包里给我们准备了Instant类,也能拿秒

// 创建Instant对象

Instant instant = Instant.now();

// 获取秒

long currentSecond = instant.getEpochSecond();

// 获取毫秒

long currentMilli = instant.toEpochMilli();

//常用

long l = System.currentTimeMillis();

输出情况

当然最后这个System类还是牛逼的,毕竟在系统类里。

时间戳

格林威治时间1970年01月01日00时00分00秒到现在的总秒数,共10位,单位为秒

注意:Java生成的时间戳是13位,单位是毫秒

如果还想拿更精确的秒,System里还有一个nanoTime可以用

tips(阿里巴巴开发手册推荐):

在JDK8中,针对统计时间等场景,推荐使用Instant类

修改时间

java.time下的LocalDate、LocalTime、LocalDateTime、Instant类实例的修改方法

我们直接用LocalDate实例点一下发现他里面封装了很多方法

咱这一个一个讲也没必要,大多数都是望文生义,比如plusDays,那自然是在当前日期加天数,得到加完后的日期是哪天

怕了吗,加十天国庆假期直接结束。

还有像什么firstDayOfYear(一年当中第一天是几号)等等不再赘述,另外几个类中也有相似的很多方法。

格式化输出

说道日期的格式化输出,大家第一个想到的肯定是

SimpleDateFormat

他的用法不尽其数,但是只要知道yyyy-dd-mm–hh-mm-ss之间的关系,想怎么输出就怎么输出。

import java.text.SimpleDateFormat;

import java.util.Date;

/**

*

firstIdeaProject

*

*

* @author : Nicer_feng

* @date : 2020-09-28 10:21

**/

public class SimpleDateFormatDemo {

public static void main(String[] args) {

SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");

SimpleDateFormat myFmt1=new SimpleDateFormat("yy/MM/dd HH:mm");

SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//等价于now.toLocaleString()

SimpleDateFormat myFmt3=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E ");

SimpleDateFormat myFmt4=new SimpleDateFormat("一年中的第 D 天 一年中第w个星期 一月中第W个星期 在一天中k时 z时区");

SimpleDateFormat myFmt5=new SimpleDateFormat("今年是yyyy,这个月是MM月了,今天是dd号啊");

Date now=new Date();

System.out.println(myFmt.format(now));

System.out.println(myFmt1.format(now));

System.out.println(myFmt2.format(now));

System.out.println(myFmt3.format(now));

System.out.println(myFmt4.format(now));

System.out.println(myFmt5.format(now));

System.out.println(now.toString());

System.out.println(now.toGMTString());

System.out.println(now.toLocaleString());

}

}

注意这里的最后两个方法都已经过时了,输出结果如下

下面总结在SimpleDateFormat中各个字母的意思

SimpleDateFormat函数变量/模式字母

G 年代标志符 y 年 M 月 d 日 h 时 在上午或下午 (1~12) H 时 在一天中 (0~23) m 分 s 秒 S 毫秒 E 星期 D 一年中的第几天 F 一月中第几个星期几 w 一年中第几个星期 W 一月中第几个星期 a 上午 / 下午 标记符 k 时 在一天中 (1~24) K 时 在上午或下午 (0~11) z 时区

更全的可以见JDK8API中的SimpleDateFormat类

https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

讲了这么多SimpleDateFormat,但其实在JDK8中,是不推荐使用的,为什么,因为SimpleDateFormat是线程不安全的。所以我们在JDK8应用中推荐用Instant代替Date,LocalDateTime带Calendar,DateTimeFormatter代替SimpleDateFormat,官方解释是simple beautiful strong immutable thread-safe。

DateTimeFormatter(重要)

跟上面的SimpleDateFormat函数变量基本无异,写一个简单的demo

LocalDate localDate = LocalDate.now();

String format1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);

//yyyyMMdd

String format2 = localDate.format(DateTimeFormatter.ISO_DATE);

//yyyy-MM-dd

//2.LocalTime --> String

LocalTime localTime = LocalTime.now();

String format3 = localTime.format(DateTimeFormatter.ISO_TIME);

//20:19:22.42

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");

String format4 = localTime.format(formatter);

//3.LocalDateTime --> String

LocalDateTime localDateTime = LocalDateTime.now();

DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

String format5 = localDateTime.format(formatter2);

System.out.println(format1);

System.out.println(format2);

System.out.println(format3);

System.out.println(format4);

System.out.println(format5);

输出

这个DateTimeFormatter甚至能按照当地习惯来输出

LocalDateTime localDateTime = LocalDateTime.now();

DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy MMM dd EE HH:mm", Locale.CHINA);

String format5 = localDateTime.format(formatter2);

输出

但是官方给我们弄得总是不符合我们心里预期,所以这里推荐自己封装DateTimeUtils类来调用

DateTimeUtils封装

DateTimeUtils.java

package TimeUtilssss;

import java.time.*;

import java.time.format.DateTimeFormatter;

import java.time.temporal.ChronoUnit;

/**

*

firstIdeaProject

*

*

* @author : Nicer_feng

* @date : 2020-09-28 10:48

**/

public class DateTimeUtils {

public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HHmmss");

public static final DateTimeFormatter YEAR_MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM");

public static final DateTimeFormatter SHORT_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyMMdd");

public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

public static final DateTimeFormatter SHORT_DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyMMddHHmmss");

public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

public static final DateTimeFormatter LONG_DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS");

/**

* 返回当前的日期

*/

public static LocalDate getCurrentLocalDate() {

return LocalDate.now();

}

/**

* 返回当前时间

*/

public static LocalTime getCurrentLocalTime() {

return LocalTime.now();

}

/**

* 返回当前日期时间

*/

public static LocalDateTime getCurrentLocalDateTime() {

return LocalDateTime.now();

}

/**

* yyyy-MM-dd

*/

public static String getCurrentDateStr() {

return LocalDate.now().format(DATE_FORMATTER);

}

/**

* yyMMdd

*/

public static String getCurrentShortDateStr() {

return LocalDate.now().format(SHORT_DATE_FORMATTER);

}

public static String getCurrentMonthStr() {

return LocalDate.now().format(YEAR_MONTH_FORMATTER);

}

/**

* yyyy-MM-dd HH:mm:ss

*/

public static String getCurrentDateTimeStr() {

return LocalDateTime.now().format(DATETIME_FORMATTER);

}

public static String getCurrentLongDateTimeStr(){

return LocalDateTime.now().format(LONG_DATETIME_FORMATTER);

}

/**

* yyMMddHHmmss

*/

public static String getCurrentShortDateTimeStr() {

return LocalDateTime.now().format(SHORT_DATETIME_FORMATTER);

}

/**

* HHmmss

*/

public static String getCurrentTimeStr() {

return LocalTime.now().format(TIME_FORMATTER);

}

public static String getCurrentDateStr(String pattern) {

return LocalDate.now().format(DateTimeFormatter.ofPattern(pattern));

}

public static String getCurrentDateTimeStr(String pattern) {

return LocalDateTime.now().format(DateTimeFormatter.ofPattern(pattern));

}

public static String getCurrentTimeStr(String pattern) {

return LocalTime.now().format(DateTimeFormatter.ofPattern(pattern));

}

public static LocalDate parseLocalDate(String dateStr, String pattern) {

return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(pattern));

}

public static LocalDateTime parseLocalDateTime(String dateTimeStr, String pattern) {

return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(pattern));

}

public static LocalTime parseLocalTime(String timeStr, String pattern) {

return LocalTime.parse(timeStr, DateTimeFormatter.ofPattern(pattern));

}

public static String formatLocalDate(LocalDate date, String pattern) {

return date.format(DateTimeFormatter.ofPattern(pattern));

}

public static String formatLocalDateTime(LocalDateTime datetime, String pattern) {

return datetime.format(DateTimeFormatter.ofPattern(pattern));

}

public static String formatLocalTime(LocalTime time, String pattern) {

return time.format(DateTimeFormatter.ofPattern(pattern));

}

public static LocalDate parseLocalDate(String dateStr) {

return LocalDate.parse(dateStr, DATE_FORMATTER);

}

public static LocalDateTime parseLocalDateTime(String dateTimeStr) {

return LocalDateTime.parse(dateTimeStr, DATETIME_FORMATTER);

}

public static LocalDateTime parseLongLocalDateTime(String longDateTimeStr){

return LocalDateTime.parse(longDateTimeStr, LONG_DATETIME_FORMATTER);

}

public static LocalTime parseLocalTime(String timeStr) {

return LocalTime.parse(timeStr, TIME_FORMATTER);

}

public static String formatLocalDate(LocalDate date) {

return date.format(DATE_FORMATTER);

}

public static String formatLocalDateTime(LocalDateTime datetime) {

return datetime.format(DATETIME_FORMATTER);

}

public static String formatLocalTime(LocalTime time) {

return time.format(TIME_FORMATTER);

}

/**

* 日期相隔秒

*/

public static long periodHours(LocalDateTime startDateTime,LocalDateTime endDateTime){

return Duration.between(startDateTime, endDateTime).get(ChronoUnit.SECONDS);

}

/**

* 日期相隔天数

*/

public static long periodDays(LocalDate startDate, LocalDate endDate) {

return startDate.until(endDate, ChronoUnit.DAYS);

}

/**

* 日期相隔周数

*/

public static long periodWeeks(LocalDate startDate, LocalDate endDate) {

return startDate.until(endDate, ChronoUnit.WEEKS);

}

/**

* 日期相隔月数

*/

public static long periodMonths(LocalDate startDate, LocalDate endDate) {

return startDate.until(endDate, ChronoUnit.MONTHS);

}

/**

* 日期相隔年数

*/

public static long periodYears(LocalDate startDate, LocalDate endDate) {

return startDate.until(endDate, ChronoUnit.YEARS);

}

/**

* 是否当天

*/

public static boolean isToday(LocalDate date) {

return getCurrentLocalDate().equals(date);

}

/**

* 获取当前毫秒数

*/

public static Long toEpochMilli(LocalDateTime dateTime) {

return dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

}

/**

* 判断是否为闰年

*/

public static boolean isLeapYear(LocalDate localDate){

return localDate.isLeapYear();

}

}

实例化LocalDate类后直接format调用即可

时间戳格式化

拿到Java中13位时间戳以后,我们可以做啥?

long l = System.currentTimeMillis();

System.out.println(l);

//输出 1601260690773

刚才说正常的时间戳是10位,Java中多的3位是毫秒级别,如果不要毫秒直接输出咋办?当然是丢掉后面3位啦,你可以直接除1000,或者把时间戳转为字符串,只拿前十位

long l = System.currentTimeMillis();

System.out.println(l);

System.out.println(l/1000);

String l1 = (l + "").substring(0, 10);

System.out.println(l1);

咱时间戳也是可以直接用SimpleDateFormat 来格式化的,这里做个示范,其他具体操作可以看上面的

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String s = format.format(l);

System.out.println(s);

参考资料:

阿里巴巴Java开发手册泰山版

DateTimeUtil工具类来自

https://blog.csdn.net/tanhongwei1994/article/details/86680845