java8 时间api是 JSR-30的实现.
原则
•
不变性:新的日期/时间 API 中,所有的类都是不可变的,这对多线程环境有好处。
•
关注点分离:新的 API 将人可读的日期时间和机器时间(unix timestamp)明确分离,它为日期(Date)、时间
•
(Time)、日期时间(DateTime)、时间戳(unix timestamp)以及时区定义了不同的类。
•
清晰:在所有的类中,方法都被明确定义用以完成相同的行为。举个例子,要拿到当前实例我们可以使用 now()方
•
法,在所有的类中都定义了 format()和 parse()方法,而不是像以前那样专门有一个独立的类。为了更好的处理问
•
题,所有的类都使用了工厂模式和策略模式,一旦你使用了其中某个类的方法,与其他类协同工作并不困难。
•
实用操作:所有新的日期/时间 API 类都实现了一系列方法用以完成通用的任务,如:加、减、格式化、解析、从
•
日期/时间中提取单独部分,等等。
•
可扩展性:新的日期/时间 API 是工作在 ISO-8601 日历系统上的,但我们也可以将其应用在非 ISO 的日历上
线程安全
数据库类型 timeStamp 用sql的类timeStamp存, new TimeStamp(System.millils()) 就可以.
直接用java8的时间就行了,以前的不用记.
时间戳to时间
long millis = System.currentTimeMillis();
LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.of("Asia/ShangHai"));
时间to时间戳
long l = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
LocalTime
isAfter()
@Test
public void testLocalTime() {
LocalTime lt = LocalTime.now();
System.out.println("当前时间到毫秒" + lt + ";时间" + lt.getHour() + ":" + lt.getMinute() + ":" + lt.getSecond() + "." + lt.getNano());
}
LocalDate
@Test
public void testLocalDate() {
LocalDate ld = LocalDate.now();//等价于LocalDate.now(Clock.systemDefaultZone())
System.out.println("日期:" + ld + ";年:" + ld.getYear() + ";月:" + ld.getMonthValue() + ";月中天:" + ld.getDayOfMonth() + "\n" +
"年中天:" + ld.getDayOfYear() + ";周中天:" + ld.getDayOfWeek() + ";是否闰年:" + ld.isLeapYear() + ";月份天数:" + ld.lengthOfMonth() + "\n" +
";年天数:" + ld.lengthOfYear()
);
LocalDate a = LocalDate.of(2012, 7, 2);
LocalDate b = LocalDate.of(2012, 7, 2);
System.out.println("a在b之后吗?" + a.isAfter(b) + "\n" + "a在b之前吗?" + a.isBefore(b) + "\n" + "a和b同一天吗?" + a.isEqual(b));
}
DateTimeFormatter
所有类型的时间的 格式化 和 解析 都靠它
public static LocalDate parse(CharSequence text, DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.parse(text, LocalDate::from);
}
@Override // override for Javadoc and performance
public String format(DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.format(this);
}
格式化时间
@Test
public void testFormat() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss E");
LocalDateTime ldt = LocalDateTime.now();
String strDate = ldt.format(dtf);
System.out.println(strDate);
}
package com.journaldev.java8.time;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateParseFormatExample {
public static void main(String[] args) {
//Format examples
LocalDate date = LocalDate.now();
//default format
System.out.println("Default format of LocalDate="+date);
//specific format
System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));
LocalDateTime dateTime = LocalDateTime.now();
//default format
System.out.println("Default format of LocalDateTime="+dateTime);
//specific format
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));
System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));
Instant timestamp = Instant.now();
//default format
System.out.println("Default format of Instant="+timestamp);
//Parse examples
LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48",
DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"));
System.out.println("Default format after parsing = "+dt);
}
}
输出:
Default format of LocalDate=2014-04-28
28::Apr::2014
20140428
Default format of LocalDateTime=2014-04-28T16:25:49.341
28::Apr::2014 16::25::49
20140428
Default format of Instant=2014-04-28T23:25:49.342Z
Default format after parsing = 2014-04-27T21:39:48
LocalDateTime 转 Date
LocalDateTime localDateTime=LocalDateTime.now()
Date date = Date.from(localDateTime.atZone( ZoneId.systemDefault()).toInstant());
Date 转 LocalDateTime
Date startDate=new Date();
LocalDateTime localDateTime = startDate.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime()
如何取得从1970年1月1日0时0分0 秒到现在的毫秒数?
1.
Calendar.getInstance().getTimeInMillis(); //第一种方式
2.
System.currentTimeMillis(); //第二种方式
3.
// Java 8
4.
Clock.systemDefaultZone().millis();
Year
@Test
public void testYear() {
Year y = Year.now();
System.out.println("天数:" + y.length() + ";是否闰年:" + y.isLeap() + ";年份值:" + y.getValue());
}
Instant 时间戳
Duration 持续时间、时间差
LocalDate 只包含日期,比如:2018-09-24
LocalTime 只包含时间,比如:10:32:10
LocalDateTime 包含日期和时间,比如:2018-09-24 10:32:10
Peroid 时间段
ZoneOffset 时区偏移量,比如:+8:00
ZonedDateTime 带时区的日期时间
Clock 时钟,可用于获取当前时间戳
java.time.format.DateTimeFormatter 时间格式化类
如何取得某月的最后一天?
LocalDate today = LocalDate.now();
//本月的第一天
LocalDate firstday = LocalDate.of(today.getYear(),today.getMonth(),1);
//本月的最后一天
LocalDate lastDay =today.with(TemporalAdjusters.lastDayOfMonth());
System.out.println("本月的第一天"+firstday);
System.out.println("本月的最后一天"+lastDay);
获取当前时间
LocalDateTime.now()
当前时间戳
long endtime = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
新版时间
java.time.temporal包:这个包包含一些时态对象,我们可以用其找出关于日期/时间对象的某个特定日期或时间,
比如说,可以找到某月的第一天或最后一天。你可以非常容易地认出这些方法,因为它们都具有“withXXX”的格
式。
没有了calendar日历类,时间的加减都集成在了时间类里
时间类有三个:分别是Date , Time , DateTime ,都继承自Temporal
Duration 计算时间差值的,之后能把时间差转为 天、小时、分钟、秒、毫秒、纳秒。 带正负,自带个abs()函数。没有小数。转成秒的话是全转。
Year 是一个单独了类,Year.now() 然后可以获取年的天数,是不是闰年等等。
许多类的实例化方法都是类的静态方法,而不是用new了
TimeZone 时区
Instant
一瞬间,指一个时间点. 获取毫秒数
Period
ISO-8601日历系统中基于日期的时间量,也就是时间段. 例如“2年、3个月和4天”。
旧版时间
Date 类
类 Date 表示特定的瞬间,精确到毫秒。 Calendar 和 SimpleDateFormat 的粘合剂,而且用long表示时间本身也能做好多事情。
构造函数:
Date() //分配 Date 对象并初始化此对象,以表示分配它的时间(精确到毫秒)。
Date(long date) //分配 Date 对象并初始化此对象,以表示自从标准基准时间(称为“历元(epoch)”,即 1970 年 1 月 1 日 00:00:00 GMT)以来的指定毫秒数。
void setTime(long time)
设置此 Date 对象,以表示 1970 年 1 月 1 日 00:00:00 GMT 以后 time 毫秒的时间点。
long getTime()
返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
boolean after(Date when)
测试此日期是否在指定日期之后。
boolean before(Date when)
测试此日期是否在指定日期之前。
Object clone()
返回此对象的副本。
int compareTo(Date anotherDate)
比较两个日期的顺序。
boolean equals(Object obj)
比较两个日期的相等性。
Date date2 = new Date(1000000000000l);
System.out.println(date2); //Sun Sep 09 09:46:40 CST 2001
SimpleDateFormat 类
将Date转成自定义格式字符串将字符串解析成Date
构造方法:
SimpleDateFormat()
用默认的模式和默认语言环境的日期格式符号构造 SimpleDateFormat。
SimpleDateFormat(String pattern)
用给定的模式和默认语言环境的日期格式符号构造 SimpleDateFormat。
SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)
用给定的模式和日期符号构造 SimpleDateFormat。
SimpleDateFormat(String pattern, Locale locale)
用给定的模式和给定语言环境的默认日期格式符号构造 SimpleDateFormat。
StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos)
将给定的 Date 格式化为日期/时间字符串,并将结果添加到给定的 StringBuffer。
Date parse(String text, ParsePosition pos)
解析字符串的文本,生成 Date。
例子:
String pattern = "yyyy年MM月dd日 HH:mm:ss:S";
SimpleDateFormat df = new SimpleDateFormat(pattern);
String result = df.format(1000000000000L); //这里传date类型和long都行。 //格式化
System.out.println(result); //2019年07月30日 09:00:45:860
Date date = df.parse(result); //解析日期字符串到Date类型
System.out.println(date); //Sun Sep 09 09:46:40 CST 2001
calendar 类
日历类,实现时间和日期的加减。
月份是从0到11,其它都是从1开始的
构造函数:
protected Calendar()
构造一个带有默认时区和语言环境的 Calendar。
protected Calendar(TimeZone zone, Locale aLocale)
构造一个带有指定时区和语言环境的 Calendar。
static Calendar getInstance() //以当前时间构造日历
与Date互转:
void setTime(Date date)
使用给定的 Date 设置此 Calendar 的时间。
Date getTime()
返回一个表示此 Calendar 时间值(从历元至现在的毫秒偏移量)的 Date 对象。
操作时间:
System.out.println(c.get(Calendar.DAY_OF_MONTH));
c.set(Calendar.YEAR, 2020);
c.add(Calendar.YEAR, 10); //随便加都没事,溢出了会进位。
//第二月有几天
Calendar time = Calendar.getInstance();
time.set(1998,2,1);
time.add(Calendar.DAY_OF_MONTH,-1);
SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd");
System.out.println("dateFormat = " + dateFormat.format(time.getTime()));
//自己活了几天了
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
Date brithDay = null;
try {
brithDay = dateFormat.parse("1994-07-28");
} catch (ParseException e) {
System.out.println("e.getMessage() = " + e.getMessage());
}
Date now = new Date();
System.out.println("(now.getTime()-brithDay.get) = " + (now.getTime() - brithDay.getTime()) / 1000 / 60 / 60 / 24);
//昨天的现在
Calendar time = Calendar.getInstance();
time.add(Calendar.DAY_OF_MONTH,-1);
SimpleDateFormat dateFormat=new SimpleDateFormat("YYYY-MM-dd HH:mm:ss:SS");
System.out.println("dateFormat.format(time.getTime()) = " + dateFormat.format(time.getTime()));
public static long currentTimeMillis() //获取系统时间(毫秒)
评论区