- Java8 以前的时间处理采用java.util.Date
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
//获取Date对象,存放的是时间戳
Date date = new Date();
//时间转时间戳(毫秒)
long timestamp = date.getTime();
System.out.println("当前时间戳: " + timestamp);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//当前GMT(格林威治)时间
System.out.println("GMT时间: " + date.toGMTString());
//当前计算机系统所在时区的时间
System.out.println("本地(东八区)时间: " + dateFormat.format(date));
//东八区时间转换成东九区(东京)时间,需要设置时区
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo"));
System.out.println("东京(东九区)时间: " + dateFormat.format(date));
//时间戳转成string
String fotmatString = dateFormat.format(timestamp);
System.out.println("时间戳转化成String: " + fotmatString);
//或者
Date date = new Date(timestamp);
String fotmatString = dateFormat.format(date);
System.out.println("时间戳转化成String: " + fotmatString);
//时间string转成date
Date parseDate = dateFormat.parse(fotmatString);
System.out.println("String转化成Date: " + parseDate);
//计算时间差(秒)
long startTime = date.getTime();
long currentTime = new Date().getTime();
long interval = (currentTime-startTime)/1000;
java.util.Date方法:
方法 | 描述 |
boolean after(Date date) | 测试当前日期是否在给定日期之后。 |
boolean before(Date date) | 测试当前日期是否早于给定日期。 |
Object clone() | 返回当前日期的克隆对象。 |
int compareTo(Date date) | 比较当前日期和给定日期。 |
boolean equals(Date date) | 比较当前日期与给定日期是否相等。 |
static Date from(Instant instant) | 从即时日期返回Date对象的实例。 |
long getTime() | 返回此日期对象表示的时间。 |
int hashCode() | 返回此日期对象的哈希码值。 |
void setTime(long time) | 将当前日期和时间更改为给定时间。 |
Instant toInstant() | 将当前日期转换为Instant对象。 |
String toString() | 将此日期转换为Instant对象。 |
- Java8 之后的时间处理采用java.time.LocalDateTime
从Java8开始,推出了LocalDate、LocalTime、LocalDateTime这三个工具类,实现了更好地时间处理。
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
//获取当前时区的日期
LocalDate localDate = LocalDate.now();
System.out.println("localDate: " + localDate);
//获取当前时区的时间
LocalTime localTime = LocalTime.now();
System.out.println("localTime: " + localTime);
//根据上面两个对象,获取日期时间
LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
System.out.println("localDateTime: " + localDateTime);
//获取当前时区的日期时间
LocalDateTime localDateTime2 = LocalDateTime.now();
System.out.println("localDateTime2: " + localDateTime2);
//格式化时间
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");
System.out.println("格式化之后的时间: " + localDateTime2.format(formatter));
//转化为时间戳(秒)
long epochSecond = localDateTime2.toEpochSecond(ZoneOffset.of("+8"));
System.out.println("时间戳为:(秒) " + epochSecond);
//转化为时间戳(毫秒)
long epochMilli = localDateTime2.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli();
System.out.println("时间戳为:(毫秒): " + epochMilli);
//时间戳(毫秒)转化成LocalDateTime
Instant instant = Instant.ofEpochMilli(epochMilli);
LocalDateTime localDateTime3 = LocalDateTime.ofInstant(instant, ZoneOffset.systemDefault());
System.out.println("时间戳(毫秒)转化成LocalDateTime: " + localDateTime3.format(formatter));
//时间戳(秒)转化成LocalDateTime
Instant instant2 = Instant.ofEpochSecond(epochSecond);
LocalDateTime localDateTime4 = LocalDateTime.ofInstant(instant2, ZoneOffset.systemDefault());
System.out.println("时间戳(秒)转化成LocalDateTime: " + localDateTime4.format(formatter));
//字符串转LocalDateTime
String str = "1986-04-08 12:30:00";
LocalDateTime localDateTime5 = LocalDateTime.parse(str, formatter);
String str2 = "1986-04-08T12:30:00";
LocalDateTime localDateTime6 = LocalDateTime.parse(str2);
//获取星期
DayOfWeek week = localDateTime5.getDayOfWeek();
System.out.println("星期: " + week.getValue());
//计算间隔时间
Duration duration = Duration.between(dateTime, LocalDateTime.now());
Integer days = duration.toDays();
时间增减
LocalDateTime newdatetime = LocalDateTime.plusYears(long hours); //年
LocalDateTime newdatetime = LocalDateTime.plusMonths(long hours); //月
LocalDateTime newdatetime = LocalDateTime.plusDays(long hours); //日
LocalDateTime newdatetime = LocalDateTime.plusHours(long hours); //时
LocalDateTime newdatetime = LocalDateTime.plusMinutes(long hours); //分
LocalDateTime newdatetime = LocalDateTime.plusSeconds(long hours); //秒
LocalDateTime newdatetime = LocalDateTime.plusNanos(long hours); //纳秒
LocalDateTime newdatetime = LocalDateTime.plusWeeks(long hours); //星期
LocalDateTime newdatetime = LocalDateTime.plus(TemporalAmount amountToAdd) //要添加的数量
LocalDateTime newdatetime = LocalDateTime.plus(long amountToAdd, TemporalUnit unit) //amountToAdd:要添加的数量,unit:要添加的单位
- LocalDateTime和Date转换
// Date 转化成 LocalDateTime
public static LocalDateTime dateToLocalDate(Date date) {
Instant instant = date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
return instant.atZone(zoneId).toLocalDateTime();
}
// LocalDateTime 转化成 Date
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = localDateTime.atZone(zoneId);
return Date.from(zdt.toInstant());
}
java.time.LocalDateTime方法:
方法 | 描述 |
Temporal adjustInto(Temporal temporal) | 调整指定的时态对象以使其具有与此对象相同的日期和时间。 |
OffsetDateTime atOffset(ZoneOffset offset) | 将此日期时间与偏移时间组合以创建OffsetDateTime。 |
ZonedDateTime atZone(ZoneId zone) | 将此日期时间与时区组合以创建ZonedDateTime。 |
int compareTo(ChronoLocalDateTime<?> other) | 将此日期时间与另一个日期时间进行比较。 |
boolean equals(Object obj) | 检查此日期时间是否等于另一个日期时间。 |
String format(DateTimeFormatter formatter) | 使用指定的格式化程序格式化此日期时间。 |
static LocalDateTime from(TemporalAccessor temporal) | 从时态对象获取LocalDateTime的实例。 |
int get(TemporalField field) | 从此日期时间获取指定字段的值作为int类型值。 |
int getDayOfMonth() | 获取日期字段。 |
DayOfWeek getDayOfWeek() | 获取星期几字段,即枚举DayOfWeek。 |
int getDayOfYear() | 获取日期字段。 |
int getHour() | 获取当日时间字段。 |
long getLong(TemporalField field) | 从此日期时间获取指定字段的值为long值。 |
Month getMinute() | 获取分钟字段。 |
Month getMonth() | 使用Month枚举获取月份字段。 |
int getMonthValue() | 获取1到12之间的月份字段。 |
int getNano() | 获取纳秒级字段。 |
int getSecond() | 获取秒钟字段。 |
int getYear() | 获取年份字段。 |
int hashCode() | 此日期时间的哈希码。 |
boolean isAfter(ChronoLocalDateTime<?> other) | 检查此日期时间是否在指定的日期时间之后。 |
boolean isBefore(ChronoLocalDateTime<?> other) | 检查此日期时间是否在指定的日期时间之前。 |
boolean isEqual(ChronoLocalDateTime<?> other) | 检查此日期时间是否等于指定的日期时间。 |
boolean isSupported(TemporalField field) | 检查是否支持指定的字段。 |
boolean isSupported(TemporalUnit unit) | 检查指定的单元是否受支持。 |
LocalDateTime minus(long amountToSubtract, TemporalUnit unit) | 返回此日期时间的副本,并减去指定的数量。 |
LocalDateTime minus(TemporalAmount amountToSubtract) | 返回此日期时间的副本,并减去指定的数量。 |
LocalDateTime minusDays(long daysToSubtract) | 返回此LocalDateTime的副本,并减去指定的天数。 |
LocalDateTime minusHours(long hoursToSubtract) | 返回此LocalDateTime的副本,并减去指定的小时数。 |
LocalDateTime minusMinutes(long minutesToSubtract) | 返回此LocalDateTime的副本,并减去指定的分钟数。 |
LocalDateTime minusMonths(long monthsToSubtract) | 返回此LocalDateTime的副本,并减去指定的月数。 |
LocalDateTime minusNanos(long nanos) | 返回此LocalDateTime的副本,减去指定的纳秒数。 |
LocalDateTime minusSeconds(long seconds) | 返回此LocalDateTime的副本,并减去指定的秒数。 |
LocalDateTime minusWeeks(long weeksToSubtract) | 返回此LocalDateTime的副本,并减去指定的周数。 |
LocalDateTime minusYears(long yearsToSubtract) | 返回此LocalDateTime的副本,并减去指定的年数。 |
static LocalDateTime now() | 从默认时区中的系统时钟获取当前日期时间。 |
static LocalDateTime now(Clock clock) | 从指定的时钟获得当前日期时间。 |
static LocalDateTime now(ZoneId zone) | 从指定时区的系统时钟获取当前日期时间。 |
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute) | 从年,月,日,小时和分钟获得LocalDateTime的实例,将秒钟和纳秒设置为零。 |
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second) | 从年,月,日,小时,分钟和秒获得LocalDateTime的实例,将纳秒设置为零。 |
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) | 从年,月,日,小时,分钟,秒和纳秒获得LocalDateTime的实例。 |
static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second) | 从年,月,日,小时,分钟和秒获得LocalDateTime的实例,将纳秒设置为零。 |
static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) | 从年,月,日,小时,分钟,秒和纳秒获得LocalDateTime的实例。 |
static LocalDateTime of(LocalDate date, LocalTime time) | 从日期和时间获取LocalDateTime的实例。 |
static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset) | 从1970-01-01T00:00:00Z的纪元获得LocalDateTime的实例。 |
static LocalDateTime ofInstant(Instant instant, ZoneId zone) | 从Instant和区域ID获取LocalDateTime的实例。 |
static LocalDateTime parse(CharSequence text) | 从文本字符串中获取LocalDateTime的实例,例如2007-12-03 T10:15:30。 |
static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter) | 使用特定格式化程序从文本字符串中获取LocalDateTime的实例。 |
LocalDateTime plus(long amountToAdd, TemporalUnit unit) | 返回此日期时间的副本,并添加指定的数量。 |
LocalDateTime plus(TemporalAmount amountToAdd) | 返回此日期时间的副本,并添加指定的数量。 |
LocalDateTime plusDays(long daysToAdd) | 返回此LocalDateTime的副本,并添加指定的天数。 |
LocalDateTime plusHours(long hoursToAdd) | 返回此LocalDateTime的副本,并添加指定的小时数。 |
LocalDateTime plusMinutes(long minutesToAdd) | 返回此LocalDateTime的副本,并添加指定的分钟数。 |
LocalDateTime plusMonths(long monthsToAdd) | 返回此LocalDateTime的副本,并添加指定的月份数。 |
LocalDateTime plusNanos(long nanos) | 返回此LocalDateTime的副本,其中添加了指定的纳秒数。 |
LocalDateTime plusSeconds(long seconds) | 返回此LocalDateTime的副本,并添加指定的秒数。 |
LocalDateTime plusWeeks(long weeksToAdd) | 返回此LocalDateTime的副本,并添加指定的周数。 |
LocalDateTime plusYears(long yearsToAdd) | 返回此LocalDateTime的副本,其中添加了指定的年数。 |
<R> R query(TemporalQuery<R> query) | 使用指定的查询查询此日期时间。 |
ValueRange range(TemporalField field) | 获取指定字段的有效值范围。 |
LocalDate toLocalDate() | 获取此日期时间的LocalDate部分。 |
LocalTime toLocalTime() | 获取此日期时间的LocalTime部分。 |
String toString() | 将此日期输出为字符串,例如2007-12-03T10:15:30。 |
LocalDateTime truncatedTo(TemporalUnit unit) | 返回此LocalDateTime的副本,并截断时间。 |
long until(Temporal endExclusive, TemporalUnit unit) | 根据指定的单位计算到另一个日期时间的时间量。 |
LocalDateTime with(TemporalAdjuster adjuster) | 返回此日期时间的调整副本。 |
LocalDateTime with(TemporalField field, long newValue) | 返回此日期时间的副本,并将指定字段设置为新值。 |
LocalDateTime withDayOfMonth(int dayOfMonth) | 返回此LocalDateTime的副本,其中包含每日更改的日期。 |
LocalDateTime withDayOfYear(int dayOfYear) | 返回此LocalDateTime的副本,其中包含日期更改。 |
LocalDateTime withHour(int hour) | 返回此LocalDateTime的副本,并更改日期。 |
LocalDateTime withMinute(int minute) | 返回此LocalDateTime的副本,并更改了分钟。 |
LocalDateTime withMonth(int month) | 返回此LocalDateTime的副本,其中包含已更改的年份。 |
LocalDateTime withNano(int nanoOfSecond) | 返回此LocalDateTime的副本,并更改了纳秒。 |
LocalDateTime withSecond(int second) | 返回此LocalDateTime的副本,并更改秒钟。 |
LocalDateTime withYear(int year) | 返回此LocalDateTime的副本,其中年份已更改。 |
- System.currentTimeMillis()
在开发过程中,通常很多人都习惯使用new Date()来获取当前时间。new Date()所做的事情其实就是调用了System.currentTimeMillis()。如果仅仅是需要或者毫秒数,那么完全可以使用System.currentTimeMillis()去代替new Date(),效率上会高一点。
//获得系统的时间,单位为毫秒
long milliSeconds = System.currentTimeMillis();
//转换为妙
long seconds = totalMilliSeconds / 1000;
- 使用java.util.Calendar获取时间戳
Calendar calendar = Calendar.getInstance();
//获取当前时间戳(毫秒)
Date date = calendar.getTime();
Long milliseconds = date.getTime();
//或者
Long milliseconds = calendar.getTimeInMillis();
System.out.println(milliseconds);
//当前时间戳(秒)
Long seconds = milliseconds/1000;
System.out.println(seconds);
//获取昨天这个时间的时间戳
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR,-1);
Long milliseconds = calendar.getTime().getTime();
System.out.println(milliseconds);
//获取今天0点的时间戳
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH),0,0,0);
Long milliseconds = calendar.getTime().getTime();
System.out.println(milliseconds);
//获取昨天0点的时间戳
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)-1,0,0,0);
Long milliseconds = calendar.getTime().getTime();
System.out.println(milliseconds);
//获取这个月1号12点的时间戳
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),1,12,0,0);
Long milliseconds = calendar.getTime().getTime();
System.out.println(milliseconds);
java.util.Calendar方法:
方法 | 描述 |
public void add(int field, int amount) | 将指定的(签名)时间量添加到给定的日历字段中。 |
public boolean after (Object when) | 如果此Calendar表示的时间晚于when对象表示的时间,则该方法返回true。 |
public boolean before(Object when) | 如果此Calendar表示的时间早于when对象表示的时间,则该方法返回true。 |
public final void clear(int field) | 设置给定的日历字段值和未定义此日历的时间值。 |
public Object clone() | 克隆方法提供当前对象的副本。 |
public int compareTo(Calendar anotherCalendar) | Calendar类的compareTo() 方法比较两个日历对象之间的时间值(毫秒偏移量)。 |
protected void complete() | 它将填充日历字段中所有未设置的字段。 |
protected abstract void computeFields() | 它将当前毫秒时间值time转换为fields[]中的日历字段值。 |
protected abstract void computeTime() | 它将fields[]中的当前日历字段值转换为毫秒时间值time。 |
public boolean equals(Object object) | equals() 方法比较两个对象是否相等,如果相等,则返回true。 |
public int get(int field) | 在get() 方法中,将日历的字段作为参数传递,并且此方法返回作为参数传递的字段的值。 |
public int getActualMaximum(int field) | 返回作为参数传递给getActualMaximum() 方法的日历字段的最大可能值。 |
public int getActualMinimum(int field) | 返回作为参数传递给getActualMinimum() 方法的日历字段的最小可能值。 |
public static Set<String> getAvailableCalendarTypes() | 返回一个包含Java Runtime Environment支持的所有可用日历类型的字符串集的集合。 |
public static Locale[] getAvailableLocales() | 返回Java运行时环境中所有可用语言环境的数组。 |
public String getCalendarType() | 以字符串形式返回Java Runtime Environment支持的所有可用日历类型。 |
public String getDisplayName(int field, int style, Locale locale) | 返回以给定样式和本地形式作为参数传递的日历字段值的String表示形式。 |
public Map<String,Integer> getDisplayNames(int field, int style, Locale locale) | 返回给定样式和本地作为参数传递的日历字段值的Map表示形式。 |
public int getFirstDayOfWeek() | 以整数形式返回一周中的第一天。 |
public abstract int getGreatestMinimum(int field) | 此方法返回作为参数传递的Calendar字段的最高最小值。 |
public static Calendar getInstance() | 此方法与Calendar对象一起使用,以根据Java运行时环境设置的当前时区获取Calendar的实例。 |
public abstract int getLeastMaximum(int field) | 返回指定为方法参数的字段的所有最大值中的最小值。 |
public abstract int getMaximum(int field) | 此方法与日历对象一起使用,以获取指定日历字段的最大值作为参数。 |
public int getMinimalDaysInFirstWeek() | 以整数形式返回所需的最少天数。 |
public abstract int getMinimum(int field) | 此方法与日历对象一起使用,以获取指定日历字段的最小值作为参数。 |
public final Date getTime() | 此方法获取日历对象的时间值并返回日期。 |
public long getTimeInMillis() | 返回当前时间(以毫秒为单位)。此方法具有返回类型。 |
public TimeZone getTimeZone() | 此方法获取日历对象的TimeZone并返回一个TimeZone对象。 |
public int getWeeksInWeekYear() | 返回每周的总周数。年份中的星期以整数形式返回。 |
public int getWeekYear() | 此方法获取当前日历表示的星期。 |
public int hashCode() | Java中的所有其他类重载hasCode()方法。此方法返回日历对象的哈希码。 |
protected final int internalGet(int field) | 此方法返回作为参数传递的日历字段的值。 |
public boolean isLenient() | 返回布尔值。如果此日历的解释模式宽松,则为true;否则为true。否则为假。 |
public final boolean isSet(int field) | 此方法检查是否已设置指定字段作为参数。如果未设置,则返回false,否则返回true。 |
public boolean isWeekDateSupported() | 检查此日历是否支持星期日期。默认值为false。 |
public abstract void roll(int field, boolean up) | 此方法以一个单位增加或减少指定的日历字段,而不影响另一个字段 |
public void set(int field, int value) | 通过指定的值设置指定的日历字段。 |
public void setFirstDayOfWeek(int value) | 设置一周的第一天。将要设置为一周的第一天的值作为参数传递。 |
public void setMinimalDaysInFirstWeek(int value) | 设置第一周所需的最少天数。将在第一周设置为最少天数的值作为参数传递。 |
public final void setTime(Date date) | 设置当前日历对象的时间。作为参数传递的Date对象ID。 |
public void setTimeInMillis(long millis) | 设置当前时间(以毫秒为单位)。 |
public void setTimeZone(TimeZone value) | 将传递的TimeZone值(对象)设置为TimeZone作为参数。 |
public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) | 使用指定的整数值作为参数设置当前日期。这些值是weekYear,weekOfYear和dayOfWeek。 |
public final Instant toInstant() | toInstant() 方法将当前对象转换为即时对象。 |
public String toString() | 返回当前对象的字符串表示形式。 |