常用API 02
jdk8前操作时间的几个API分别为Date日期类、SimpleDateFormat格式化日期类、Calendar日历类,现在用的都是jdk8之后的LocalDate类、Localtime类、LocalDateTime类、ZoneId类(这个类是用来操作时区的)、ZonedDateTime类(同ZoneId)[这五个类用来代替jdk8前的Calendar类]。Instant类用来替代了Date类,DateTimeFormatter类用来替代SimpleDateFormat类,还有两个新补充的Period类和Duration类,这两个类用来计算时间隔。不过学习还是都得学,毕竟保不齐有老代码要维护,看不懂就寄了。
1.Date类
常用的成员方法和构造器:
示例:
import java.util.Date;
public class Datademo {
public static void main(String[] args) {
//创建一个date对象 代表系统当前时间信息。
Date date=new Date();
System.out.println(date);
System.out.println("-------------------------");
//getTime()方法可以拿到从1970.1.1 0:0:0到现在的毫秒值
System.out.println(date.getTime());
System.out.println("-------------------------");
//把时间毫秒值转化为日期对象 setTime()
long time= date.getTime();
time+=2*1000;//两秒后的时间
date.setTime(time);//修改当前系统的时间 为两秒后
System.out.println(date);
System.out.println("-------------------------");
//另一种修改时间的方式
//直接在创建对象的时候传参
Date date1=new Date(time);
System.out.println(date1);
}
}
运行结果:
很明显,这种格式可读性比较差,客户的体验也会比较差,因此我们需要用到下一个类。
2.SimpleDateformat类
常用的成员方法以及构造器
这里有个方法没有介绍到。SimpleDateFormat类还有个parse()方法,这个方法接受一个字符串类型,不过这个字符串必须是我们自己设置的格式!有一点不同都会报错的!它的用处是将我们输入的字符串解析成一个Date对象。
示例:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo {
public static void main(String[] args) throws ParseException {
//创建一个SimpleDateFormat对象并传入一个字符,这个字符代表我们自定义的格式
//format()方法返回的是String类型的
//y 表示年 M表示月 d表示日 H表示时 m表示分 s表示秒 E表示周几 a表示上午还是下午
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE a");
Date date=new Date();
System.out.println(date);
System.out.println("-----进行格式化-----");
long time= date.getTime();
//接收一个long型,表示从1970.1.1 0:0:0到一个时间的差值
String s=simpleDateFormat.format(time);
System.out.println(s);
System.out.println("------------------");
time+=1000*60*60*5;
date.setTime(time);
//接收一个日期对象,直接将日期对象按照我们自定义的格式输出
String s1=simpleDateFormat.format(date);
System.out.println(s1);
System.out.println("------------------");
//parse()方法相当于format()方法的反运算,传入我们自定义的日期类型,返回一个系统的日期类型。
Date d=simpleDateFormat.parse("2018-9-1 10:12:11 星期二 上午");
System.out.println(d);
}
}
运行结果:
3.Calendar类
常用的成员方法:
注:calendar是可变对象,一旦修改后其对象本身的时间也会产生变化!其实在第一个方法名大家可能就感觉到了,我们写单例时就会写一个getInstance()方法。
示例:
import java.util.Calendar;
import java.util.Date;
public class CalendarDemo {
public static void main(String[] args) {
//public static Calendar getInstance()方法 获取当前日历对象
Calendar now=Calendar.getInstance();
System.out.println(now);//可读性很差
System.out.println("---------------------");
//public int get(int field) 获取日历中的某个信息
int year=now.get(Calendar.YEAR);
System.out.println(year);
int month=now.get(Calendar.MONTH);
System.out.println(month);//这个输出的月份比我们现在的月份少一
System.out.println("-----------------------");
//public final Date getTime 获取日期对象
Date date=now.getTime();
System.out.println(date);
System.out.println("------------------------");
//public long getTimeInMillis() 获取时间毫秒值
long time=now.getTimeInMillis();
System.out.println("1970到现在经理了"+(time/1000/60/60/24/365)+"年");
System.out.println("------------------------");
//public void set(int field,int value) 修改日历的某个信息
// now.set(Calendar.MONTH,0);//月份改为二月份
now.set(Calendar.DAY_OF_YEAR,1);//修改成一年中的125天
System.out.println(now);
System.out.println("------------------------");
//public void add(int field,int amount) 为某个信息增加或者减少指定的值
now.add(Calendar.MONTH,3);
Date date1=now.getTime();
System.out.println(date1);
}
}
输出结果:
4.LocalDate类
常用方法:
1.public static Xxxx of():指定日期
2.public static Xxxx now()获取当前系统时间对应的该对象
3.public int getYear() 获取年
4.public int getMonteValue() 获取月份(1-12)
5.public int getDayofYear() 获取日
6.public DayofWeek getDayofWeek() 获取星期几
7.withYear()、withMonth()、withDayofMonth()、withDayofYear(): 直接修改某个信息,返回日期对象
8.plusYears()、plusMonths()、plusDays()、plusWeeks() ()给某个信息加多少,返回新日期对象
9.minusYears()、minusMonths()、minusDays()、minusWeeks(:) 把某个信息减多少,返回日期对象
10.equals()、isBefore()、isAfter(): 判断两个日期对象是否相等,在前还是在后
示例:
import java.time.LocalDate;
public class LocaldateDemo {
public static void main(String[] args) {
//public static Xxxx of()指定日期
LocalDate localDate = LocalDate.of(2021, 12, 10);
System.out.println(localDate);
System.out.println("-------------------");
//public static Xxxx now()获取当前系统时间对应的该对象
LocalDate localDate1 = LocalDate.now();
System.out.println(localDate1);
System.out.println("-------------------");
//public int getYear() 获取年
int year = localDate.getYear();
System.out.println(year);
System.out.println("-------------------");
//public int getMonteValue() 获取月份(1-12)
int month = localDate.getMonthValue();
System.out.println(month);
System.out.println("-------------------");
//public int getDayofYear() 获取日
int day = localDate.getDayOfMonth();
System.out.println(day);
System.out.println("--------------------");
//public DayofWeek getDayofWeek() 获取星期几
int dayofWeek = localDate.getDayOfWeek().getValue();
System.out.println(dayofWeek);
System.out.println("--------------------");
//withYear、withMonth、withDayofMonth、withDayofYear 直接修改某个信息,返回日期对象
LocalDate localDate2 = localDate.withYear(2003);
System.out.println(localDate2);
LocalDate localDate3 = localDate2.withMonth(10);
System.out.println(localDate3);
//plusYears、plusMonths、plusDays、plusWeeks 给某个信息加多少,返回新日期对象
LocalDate localDate4 = localDate3.plusDays(22);
System.out.println(localDate4);
LocalDate localDate5 = localDate4.plusMonths(2);
System.out.println(localDate5);
//minusYears、minusMonths、minusDays、minusWeeks 把某个信息减多少,返回日期对象
LocalDate localDate6 = localDate5.minusDays(5);
System.out.println(localDate6);
LocalDate localDate7 = localDate6.minusMonths(5);
System.out.println(localDate7);
//equals、isBefore、isAfter 判断两个日期对象是否相等,在前还是在后
System.out.println(localDate3.equals(localDate2));
System.out.println(localDate6.isAfter(localDate2));
System.out.println(localDate3.isBefore(localDate5));
}
}
输出结果:
LocalTime类、LocalDeteTime类的方法和LocalDete类几乎一样,这里直接放代码和结果了。
5.LocalTime类
示例:
import java.time.LocalTime;
public class LocalTimeDemo {
public static void main(String[] args) {
LocalTime localTime=LocalTime.now();//获取当前时间
System.out.println(localTime);
LocalTime localTime1=LocalTime.of(15,15,15);
System.out.println(localTime1);
int hour=localTime.getHour();
int min=localTime.getMinute();
int s=localTime.getSecond();
int ns=localTime.getNano();
System.out.println(hour+"\t"+min+"\t"+s+"\t"+ns+"\t");
System.out.println("-----------------");
LocalTime localTime2=localTime1.withHour(1);
LocalTime localTime3=localTime1.withMinute(11);
LocalTime localTime4=localTime1.withSecond(11);
LocalTime localTime5=localTime1.withNano(12111);
System.out.println(localTime2);
System.out.println(localTime3);
System.out.println(localTime4);
System.out.println(localTime5);
System.out.println("--------------------");
LocalTime localTime6=localTime5.plusHours(5);
LocalTime localTime7=localTime6.plusMinutes(5);
LocalTime localTime8=localTime6.plusSeconds(5);
LocalTime localTime9=localTime6.plusNanos(5);
System.out.println(localTime6);
System.out.println(localTime7);
System.out.println(localTime8);
System.out.println(localTime9);
System.out.println("---------------------");
LocalTime localTime10=localTime3.minusHours(3);
LocalTime localTime11=localTime3.minusMinutes(3);
LocalTime localTime12=localTime3.minusSeconds(55);
LocalTime localTime13=localTime3.minusNanos(55);
System.out.println(localTime10);
System.out.println(localTime11);
System.out.println(localTime12);
System.out.println(localTime13);
System.out.println("-----------------------");
System.out.println(localTime10.equals(localTime1));
System.out.println(localTime10.isAfter(localTime3));
System.out.println(localTime10.isBefore(localTime3));
}
}
运行结果:
6.LocalDemeTime类
示例:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class LocalDateTimeDemo {
public static void main(String[] args) {
LocalDateTime localDateTime=LocalDateTime.now();
System.out.println(localDateTime);
System.out.println("--------------------------");
int year=localDateTime.getYear();
int month=localDateTime.getMonthValue();
int day=localDateTime.getDayOfMonth();
int hour=localDateTime.getHour();
int min=localDateTime.getMinute();
int s=localDateTime.getSecond();
int ns=localDateTime.getNano();
System.out.println(year+"\t"+month+"\t"+day+"\t"+hour+"\t"+min+"\t"+s+"\t"+ns+"\t");
System.out.println("----------------------------");
LocalDateTime localDateTime1=localDateTime.withHour(15);
LocalDateTime localDateTime2=localDateTime1.withYear(2011);
System.out.println(localDateTime2);
System.out.println(localDateTime1);
System.out.println("-----------------------------");
LocalDateTime localDateTime3=localDateTime.plusDays(5);
LocalDateTime localDateTime4=localDateTime2.plusYears(6);
System.out.println(localDateTime3);
System.out.println(localDateTime4);
System.out.println("-----------------------------");
LocalDateTime localDateTime5=LocalDateTime.of(2022,12,2,12,2,2,121);
System.out.println(localDateTime5);
System.out.println("-----------------------------");
LocalTime localTime=localDateTime.toLocalTime();
LocalDate localDate=localDateTime.toLocalDate();
System.out.println(localDate);
System.out.println(localTime);
System.out.println("----------------------------");
LocalDateTime localDateTime6=LocalDateTime.of(localDate,localTime);
System.out.println(localDateTime6);
}
}
运行结果:
7.ZoneId类和ZonedDateTime类
常用方法:
1.public static Set getAvailableZoneIds(): 获取Java支持的全部时区Id。
2.public static ZoneId of(String zoneId) : 把某个时区id封装成ZoneId对象。
3.public static ZonedDateTime now(ZoneId zone): 获取某个时区的ZonedDateTime对象
4.public static ZonedDateTime now():获取系统默认时区的ZonedDateTime对象
5.可以通过ZonedDateTime.now(Clock.systemUTC());来获得世界标准时间
示例:
import java.time.Clock;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class ZoneIdDemo {
public static void main(String[] args) {
ZoneId zoneId = ZoneId.systemDefault();
System.out.println(zoneId.getId());
System.out.println(zoneId);
// public static Set<String> getAvailableZoneIds(): 获取Java支持的全部时区Id
System.out.println(ZoneId.getAvailableZoneIds());
// public static ZoneId of(String zoneId) : 把某个时区id封装成ZoneId对象。
ZoneId zoneId1 = ZoneId.of("America/New_York");
// 2、ZonedDateTime:带时区的时间。
// public static ZonedDateTime now(ZoneId zone): 获取某个时区的ZonedDateTime对象。
ZonedDateTime now = ZonedDateTime.now(zoneId1);
System.out.println(now);
// 世界标准时间了
ZonedDateTime now1 = ZonedDateTime.now(Clock.systemUTC());
System.out.println(now1);
// public static ZonedDateTime now():获取系统默认时区的ZonedDateTime对象
ZonedDateTime now2 = ZonedDateTime.now();
System.out.println(now2);
}
}
运行结果:
8.Instant类
常用方法:
示例:
public class Test5_Instant {
public static void main(String[] args) {
// 1、创建Instant的对象,获取此刻时间信息
Instant now = Instant.now(); // 不可变对象
// 2、获取总秒数
long second = now.getEpochSecond();
System.out.println(second);
// 3、不够1秒的纳秒数
int nano = now.getNano();
System.out.println(nano);
System.out.println(now);
Instant instant = now.plusNanos(111);
// Instant对象的作用:做代码的性能分析,或者记录用户的操作时间点
Instant now1 = Instant.now();
// 代码执行。。。。
Instant now2 = Instant.now();
LocalDateTime l = LocalDateTime.now();
}
}
运行结果:
9.DateTimeFormatter类
常用方法:
示例:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterDemo {
public static void main(String[] args) {
//创建一个日期格式化器对象出来
DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
//对时间进行格式化
LocalDateTime now=LocalDateTime.now();
System.out.println(now);
//正向格式化
String str= dtf.format(now);
System.out.println(str);
//反向格式化
String str1= now.format(dtf);
System.out.println(str1);
//解析时间:解析时间一般使用LocalDateTime提供的解析方法来解析。
String str3="2021-12-11 11-11-20";
LocalDateTime localDateTime=LocalDateTime.parse(str3,dtf);
System.out.println(localDateTime);
}
}
运行结果:
10.Period、Duration类
Period常用方法:
Duration类常用方法:
这里值得一提的是两个方法都有一个计算隔了多少天的方法,不过Period类的方法是单纯的日日相减,而不是像Duration类那样运算出了过了多少天。
示例:
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
public class PeriodDemo {
public static void main(String[] args) {
//period只会年和年相减,月和月相减,日和日相减。
LocalDate localDate=LocalDate.now();
LocalDate localDate1=LocalDate.of(2003,12,5);
Period period = Period.between(localDate1, localDate);
int year=period.getYears();//计算隔几年
int month=period.getMonths();//计算隔几个月
int day=period.getDays();//计算隔几天
System.out.println(year+"\t"+month+"\t"+day+"\t");
//Duration计算隔几天几小时是实打实的,而不是简单的day-day1得到新的day差值。
LocalDateTime start = LocalDateTime.of(2025, 1, 11, 11, 10, 10);
LocalDateTime end = LocalDateTime.of(2025, 11, 1, 11, 1, 11);
Duration duration=Duration.between(start,end);
long day1=duration.toDays();
long hour=duration.toHours();
long min=duration.toMinutes();
long s=duration.toSeconds();
long ms=duration.toMillis();
long ns=duration.toNanos();
System.out.println(day1+"\t"+hour+"\t"+min+"\t"+s+"\t"+ms+"\t"+ns+"\t");
}
}