Java------常用类(二)
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
/**
* 涉及到String类与其他结构之间的转换
*/
public class StringTest1 {
/**
* 复习
* String与基本数据类型、包装类之间的转换
*
* String --> 基本数据类型、包装类:调用包装类的静态方法:parseXxx(str)
* 基本数据类型、包装类 --> String:调用String重载的valueOf(xxx)
*/
@Test
public void test1(){
String str1 = "123";//数据存储在常量池中
// int num = (int)str1;//错误的
int num = Integer.parseInt(str1);
String str2 = String.valueOf(num); //"123
String str3 = num + "";//有变量名参与,那么 String str3数据存储在堆里
System.out.println(str2);//123
System.out.println(str1 == str3); //false
}
@Test
/**
* String 与 char[]之间的转换
*
* String --> char[]:调用String的toCharArray()
* char[] --> String:调用String的构造器
*/
public void test2(){
String str1 = "123";
// int num = (int)str1;//错误的
int num = Integer.parseInt(str1);
String str2 = String.valueOf(num); //"123
String str3 = num + "";
System.out.println(str2);//123
System.out.println(str1 == str3); //false
}
@Test
/**
* String 与 char[]之间的转换
*
* String --> char[]:调用String的toCharArray()
* char[] --> String:调用String的构造器
*/
public void test3(){
String str1 = "abc123"; //题目: a21cb3
char[] charArray = str1.toCharArray();
for (int i = 0; i < charArray.length; i++) {
System.out.println(charArray[i]);
}
char[] arr = new char[]{'h','e','l','l','o'};
String str2 = new String(arr);
System.out.println(str2);
}
@Test
/**
* String 与 byte[]之间的转换
*
* 编码:String --> byte[]:调用String的getBytes()
* 解码:byte[] --> String:调用String的构造器
*
* 编码:字符串 -->字节 (看得懂 --->看不懂的二进制数据)
* 解码:编码的逆过程,字节 --> 字符串 (看不懂的二进制数据 ---> 看得懂)
*
* 说明:解码时,要求解码使用的字符集必须与编码时使用的字符集一致,否则会出现乱码。
*
*/
public void test4() throws UnsupportedEncodingException {
String str1 = "abc123重工";
byte[] bytes = str1.getBytes();//使用默认的字符编码集,进行转换
System.out.println(Arrays.toString(bytes));
byte[] gbks = str1.getBytes("gbk");//使用gbk字符集进行编码。
System.out.println(Arrays.toString(gbks));
System.out.println("*****************************");
String str2 = new String(bytes);//使用默认的字符集,进行解码。
System.out.println(str2);
String str3 = new String(gbks);
System.out.println(str3);//出现乱码。原因:编码集和解码集不一致!
String str4 = new String(gbks,"gbk");
System.out.println(str4);//没有出现乱码。原因:编码集和解码集一致!
}
@Test
public void sss(){
final String s1 = "awdq";
String s2 = s1 + "qfqi";
String s3 = "awdqqfqi";
System.out.println(s3 == s2);
//s1此时是个常量,而不是变量,因为加了fianl
}
}
package doy2;
/**
* @author shkstart
* @create 2021-10-25 23:26
*/
import org.junit.Test;
/*
* 1.模拟一个trim方法,去除字符串两端的空格。
*
*/
public class StringExer {
// 第1题
public String myTrim(String str) {
if (str != null) {
int start = 0;// 用于记录从前往后首次索引位置不是空格的位置的索引
int end = str.length() - 1;// 用于记录从后往前首次索引位置不是空格的位置的索引
while (start < end && str.charAt(start) == ' ') {
start++;
}
while (start < end && str.charAt(end) == ' ') {
end--;
}
if (str.charAt(start) == ' ') {
return "";
}
return str.substring(start, end + 1);
}
return null;
}
@Test
public void testMyTrim() {
String str = " a ";
// str = " ";
String newStr = myTrim(str);
System.out.println("---" + newStr + "---");
}
}
StringBuffer的源码分析
package doy3;
/**
* @author shkstart
* @create 2021-10-25 23:40
*/
import org.junit.Test;
/**
* String、StringBuffer、StringBuilder三者的异同?
*
* String:不可变的字符序列;底层使用char[]存储
* StringBuffer:可变的字符序列;线程安全的,效率低;底层使用char[]存储
* StringBuilder:可变的字符序列;jdk5.0新增的,线程不安全的,效率高;底层使用char[]存储
*
*/
/**
* 关于StringBuffer和StringBuilder的使用
*/
public class StringBufferBuilderTest {
/**
*
* 源码分析:
* String str = new String();//char[] value = new char[0];
* String str1 = new String("abc");//char[] value = new char[]{'a','b','c'};
*
* StringBuffer sb1 = new StringBuffer();//char[] value = new char[16];底层创建了一个长度是16的数组。
* System.out.println(sb1.length());//
* sb1.append('a');//value[0] = 'a';
* sb1.append('b');//value[1] = 'b';
*
* StringBuffer sb2 = new StringBuffer("abc");//char[] value = new char["abc".length() + 16];
*
* //问题1.System.out.println(sb2.length());//3
* //问题2.扩容问题:如果要添加的数据底层数组盛不下了,那就需要扩容底层的数组。
* 默认情况下,扩容为原来容量的2倍 + 2,同时将原有数组中的元素复制到新的数组中。
*
* 意义:开发中建议大家使用:StringBuffer(int capacity) 或 StringBuilder(int capacity)
*
*/
@Test
public void test1(){
StringBuffer sb1 = new StringBuffer("abc");
sb1.setCharAt(0,'m');
System.out.println(sb1);
StringBuffer sb2 = new StringBuffer();
System.out.println(sb2.length()); //0
}
}
package doy3;
/**
* @author shkstart
* @create 2021-10-25 23:41
*/
import org.junit.Test;
/**
* 关于StringBuffer和StringBuilder的使用
*/
public class StringBufferBuilderTest1 {
/**
* StringBuffer的常用方法:
*
* StringBuffer append(xxx):提供了很多的append()方法,用于进行字符串拼接
* StringBuffer delete(int start,int end):删除指定位置的内容
* StringBuffer replace(int start, int end, String str):把[start,end)位置替换为str
* StringBuffer insert(int offset, xxx):在指定位置插入xxx
* StringBuffer reverse() :把当前字符序列逆转
* public int indexOf(String str)
* public String substring(int start,int end):返回一个从start开始到end索引结束的左闭右开区间的子字符串
* public int length()
* public char charAt(int n )
* public void setCharAt(int n ,char ch)
*
* 总结:
* 增:append(xxx)
* 删:delete(int start,int end)
* 改:setCharAt(int n ,char ch) / replace(int start, int end, String str)
* 查:charAt(int n )
* 插:insert(int offset, xxx)
* 长度:length();
* 遍历:for() + charAt() / toString()
*
*/
@Test
public void test2(){
StringBuffer s1 = new StringBuffer("abc");
s1.append(1);
s1.append('1');
System.out.println(s1);
// s1.delete(2,4);
// s1.replace(2,4,"hello");
// s1.insert(2,false);
// s1.reverse();
String s2 = s1.substring(1,3);
System.out.println(s1);
System.out.println(s1.length());
System.out.println(s2);
}
}
package doy3;
/**
* @author shkstart
* @create 2021-10-25 23:42
*/
import org.junit.Test;
/**
* 关于StringBuffer和StringBuilder的使用
*/
public class StringBufferBuilderTest2 {
/**
* 对比String、StringBuffer、StringBuilder三者的效率:
* 从高到低排列:StringBuilder > StringBuffer > String
*
*/
@Test
public void test3(){
//初始设置
long startTime = 0L;
long endTime = 0L;
String text = "";
StringBuffer buffer = new StringBuffer("");
StringBuilder builder = new StringBuilder("");
//开始对比
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
buffer.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuffer的执行时间:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
builder.append(String.valueOf(i));
}
endTime = System.currentTimeMillis();
System.out.println("StringBuilder的执行时间:" + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < 20000; i++) {
text = text + i;
}
endTime = System.currentTimeMillis();
System.out.println("String的执行时间:" + (endTime - startTime));
}
}
JDK 8之前的日期时间API
package doy4;
/**
* @author shkstart
* @create 2021-10-26 20:10
*/
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* JDK 8之前日期和时间的API测试
*/
public class DateTimeTest {
//1.System类中的currentTimeMillis()
@Test
public void test1(){
long time = System.currentTimeMillis();
//返回当前时间与1970年1月1日0时0分0秒之间以毫秒为单位的时间差。
//称为时间戳
System.out.println(time);
}
/**
* java.util.Date类 ---> 表示特定的瞬间,精确到毫秒
* |---java.sql.Date类
*
* 1.两个构造器的使用
* >构造器一:Date():创建一个对应当前时间的Date对象
* >构造器二:创建指定毫秒数的Date对象
* 2.两个方法的使用
* >toString():显示当前的年、月、日、时、分、秒
* >getTime():获取当前Date对象对应的毫秒数。(时间戳)
*
* 3. java.sql.Date对应着数据库中的日期类型的变量
* >如何实例化
* >如何将java.util.Date对象转换为java.sql.Date对象
*SimpleDateFormat() :默认的模式和语言环境创建对象
* public SimpleDateFormat(String pattern):该构造方法可以用参数pattern 指定的格式创建一个对象,该对象调用:
*/
@Test
public void testSimpleDateFormat() throws ParseException, ParseException {
//实例化SimpleDateFormat
// SimpleDateFormat() :默认的模式和语言环境创建对象
SimpleDateFormat sdf = new SimpleDateFormat();
//格式化:日期---》字符串
Date date = new Date();
System.out.println(date); //Sun May 10 16:34:30 CST 2020
String format = sdf.format(date);
// public String format(Date date):方法格式化时间对象date
System.out.println(format); //20-5-10 下午4:34
//解析:格式化的逆过程,字符串---》日期
String str = "19-12-18 上午11:43";
Date date1 = sdf.parse(str);
//public Date parse(String source):从给定字符串的开始解析文本,以生成 一个日期。
System.out.println(date1); //Wed Dec 18 11:43:00 CST 2019
//*************按照指定的方式格式化和解析:调用带参的构造器*****************
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
//格式化
String format1 = sdf1.format(date);
System.out.println(format1); //02020.五月.10 公元 04:32 下午
//解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现),
//否则,抛异常
Date date2 = sdf1.parse("02020.五月.10 公元 04:32 下午");
System.out.println(date2); //Sun May 10 16:32:00 CST 2020
}
/**
* java.util.Date类 ---> 表示特定的瞬间,精确到毫秒
* |---java.sql.Date类
*
* 1.两个构造器的使用
* >构造器一:Date():创建一个对应当前时间的Date对象
* >构造器二:创建指定毫秒数的Date对象
* 2.两个方法的使用
* >toString():显示当前的年、月、日、时、分、秒
* >getTime():获取当前Date对象对应的毫秒数。(时间戳)
*
* 3. java.sql.Date对应着数据库中的日期类型的变量
* >如何实例化
* >如何将java.util.Date对象转换为java.sql.Date对象
*
*/
@Test
public void test2(){
//构造器一:Date():创建一个对应当前时间的Date对象
Date date1 = new Date();
System.out.println(date1.toString()); //Tue Oct 09 20:09:11 CST 2020
//ublic String toString():返回该对象的字符串表示
System.out.println(date1.getTime()); //1589026216998
//getTime表示返回的毫秒数
//构造器二:创建指定毫秒数的Date对象
Date date2 = new Date(1589026216998L);
//Date(long date) 里面需要传输long型数据,且后面带L
System.out.println(date2.toString());
//创建java.sql.Date对象
java.sql.Date date3 = new java.sql.Date(35235325345L);
System.out.println(date3); //1971-02-13
//如何将java.util.Date对象转换为java.sql.Date对象
//情况一:
Date date4 = new java.sql.Date(2343243242323L);
java.sql.Date date5 = (java.sql.Date) date4;
//情况二:
// Date date6 = new Date();
// java.sql.Date date7 = new java.sql.Date(date6.getTime());
}
@Test
public void testExer() throws ParseException {
String birth = "2020-09-08";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
//yyyy代表的是4个位数的年数,MM表示精确到两位数的月份,dd表示精确到两位数的日数
Date date = sdf1.parse(birth);
// System.out.println(date);
java.sql.Date birthDate = new java.sql.Date(date.getTime());
System.out.println(birthDate);
}
}
package doy4;
/**
* @author shkstart
* @create 2021-10-27 14:37
*/
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
/**
* jdk 8 之前的日期时间的API测试
* 1.System类中currentTimeMillis();
* 2.java.util.Date和字类java.sql.Date
* 3.SimpleDateFormat
* 4.Calendar
*/
public class DateTime1 {
/**
* Calendar日历类的使用
*/
//DAY_OF_MONTH--->日期 DAY_OF_YEAR---->这一年的第几天
@Test
public void testCalendar(){
//1.实例化
//方式一:创建其子类(GregorianCalendar)的对象
//方式二:调用其静态方法getInstance()
Calendar calendar = Calendar.getInstance();
//这个对象并不是Calendar 自身实例,而是其子类实例,这是在getInstance方法内部其实是实例化了GregorianCalendar 对象并返回了。
// System.out.println(calendar.getClass()); //class java.util.GregorianCalendar
//2.常用方法
//get()获取
int days = calendar.get(Calendar.DAY_OF_MONTH);//获取日期
System.out.println(days); //10
System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //获取这一年的第几天//131,今天是这一年的131天
//set()设置
//calendar可变性
calendar.set(Calendar.DAY_OF_MONTH,22);//修改日期
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days); //22
//add()修改
calendar.add(Calendar.DAY_OF_MONTH,-3);
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days); //22-3 --》19
//getTime():日历类---> Date
Date date = calendar.getTime();//返回当前时间到 自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
System.out.println(date); //返回了一个Dare类型的 //Tue May 19 17:12:06 CST 2020
//setTime():Date ---> 日历类
Date date1 = new Date();
calendar.setTime(date1);
//public void setTime(long time):设置此Date对象,以表示 1970 年1月1日 00:00:00 GMT以后 time 毫秒的时间点
days = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(days); //10
}
}
package doy4;
/**
* @author shkstart
* @create 2021-10-26 20:12
*/
import org.junit.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* jdk 8 之前的日期时间的API测试
* 1.System类中currentTimeMillis();
* 2.java.util.Date和字类java.sql.Date
* 3.SimpleDateFormat
* 4.Calendar
* SimpleDateFormat() :默认的模式和语言环境创建对象
* public SimpleDateFormat(String pattern):该构造方法可以用参数pattern
* 指定的格式创建一个对象,该对象调用:
* public String format(Date date):方法格式化时间对象date
* public Date parse(String source):从给定字符串的开始解析文本,以生成一个日期。
*/
public class DateTime {
/**
* 练习1:字符串"2020-09-08"转换为java.sql.Date
*
*/
@Test
public void testExer() throws ParseException {
String birth = "2020-09-08";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf1.parse(birth);
// System.out.println(date);
java.sql.Date birthDate = new java.sql.Date(date.getTime());
//new java.sql.Date(date.getTime())是什么意思
//----->表示将java.util.Date下的date转化成毫秒数,传到java.sql.Date
System.out.println(birthDate);
}
/**
* SimpleDateFormat的使用:SimpleDateFormat对日期Date类的格式化和解析
* 1.两个操作
* 1.1格式化:日期---》字符串
* 1.2解析:格式化的逆过程,字符串---》日期
*
* 2.SimpleDateFormat的实例化
*/
@Test
public void testSimpleDateFormat() throws ParseException {
//实例化SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat();
// SimpleDateFormat() :默认的模式和语言环境创建对象-->采用默认的时间格式
//格式化:日期---》字符串
Date date = new Date();//显示当前时间
System.out.println(date); //Sun May 10 16:34:30 CST 2020
String format = sdf.format(date);
// public String format(Date date):方法格式化时间对象date 有返回值,Stirng类型的
//格式化之后是'年份'-'月份'-'日期' '上午或者下午''时间'
System.out.println(format); //20-5-10 下午4:34
//解析:格式化的逆过程,字符串---》日期
String str = "19-12-18 上午11:43";
Date date1 = sdf.parse(str);
System.out.println(date1); //Wed Dec 18 11:43:00 CST 2019
/*
至于为什么会输出Wed Dec 18 11:43:00 CST 2019这种格式的日期
因为前面一开始就--- SimpleDateFormat sdf = new SimpleDateFormat();
作用是默认的模式和语言环境创建对象-->采用默认的时间格式
而Wed Oct 27 22:20:17 CST 2021就是这种日期的格式
默认的格式------>'星期' '几月份' '日期' '时间' CST '年份'
*/
//*************按照指定的方式格式化和解析:调用带参的构造器*****************
// SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyy.MMMMM.dd GGG hh:mm aaa");
//SimpleDateFormat(String pattern)--->
//yyyy-->年 MMM---->月 dd--->日 GGG---->公元 hh--->时间 aaa---->上午或者下五
//几个字母代表单位,例:yyyyy则显02021 yyyy则显示2021
//格式化
String format1 = sdf1.format(date);
System.out.println(format1); //02020.五月.10 公元 04:32 下午
//解析:要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现),
//否则,抛异常
Date date2 = sdf1.parse("02020.五月.10 公元 04:32 下午");
//使用 public Date parse(String source):从给定字符串的开始解析文本,以生成一个日期。会抛出异常
//日期格式---->默认的格式------>'星期' '几月份' '日期' '时间' CST '年份'
System.out.println(date2); //Sun May 10 16:32:00 CST 2020
}
}
JDK8中日期时间API的介绍
import org.junit.Test;
import java.util.Date;
/**
* jdk 8中日期时间API的测试
*
*/
public class JDK8DateTimeTest {
@Test
public void testDate(){
//偏移量
Date date1 = new Date(2020,9,8);
System.out.println(date1); //Fri Oct 08 00:00:00 CST 3920
Date date2 = new Date(2020 - 1900,9 - 1,8);
System.out.println(date2); //Tue Sep 08 00:00:00 CST 2020
}
}
import org.junit.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
/**
* jdk 8中日期时间API的测试
*/
public class JDK8DateTimeTest {
/**
* LocalDate、LocalTime、LocalDateTime的使用
*
*/
@Test
public void test1(){
//now():获取当前的日期、时间、日期+时间
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate);
System.out.println(localTime);
System.out.println(localDateTime);
//of():设置指定的年、月、日、时、分、秒。没有偏移量
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
System.out.println(localDateTime1);
//getXxx():获取相关的属性
System.out.println(localDateTime.getDayOfMonth());
System.out.println(localDateTime.getDayOfWeek());
System.out.println(localDateTime.getMonth());
System.out.println(localDateTime.getMonthValue());
System.out.println(localDateTime.getMinute());
//体现不可变性
//withXxx():设置相关的属性
LocalDate localDate1 = localDate.withDayOfMonth(22);
System.out.println(localDate);
System.out.println(localDate1);
LocalDateTime localDateTime2 = localDateTime.withHour(4);
System.out.println(localDateTime);
System.out.println(localDateTime2);
//不可变性
LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
System.out.println(localDateTime);
System.out.println(localDateTime3);
LocalDateTime localDateTime4 = localDateTime.minusDays(6);
System.out.println(localDateTime);
System.out.println(localDateTime4);
}
}
import org.junit.Test;
import java.time.*;
/**
* jdk 8中日期时间API的测试
*/
public class JDK8DateTimeTest {
/**
* Instant的使用
*/
@Test
public void test2(){
//now():获取本初子午线对应的标准时间
Instant instant = Instant.now();
System.out.println(instant); //2020-05-10T09:55:55.561Z
//添加时间的偏移量
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));//东八区
System.out.println(offsetDateTime); //2020-05-10T18:00:00.641+08:00
//toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数 ---> Date类的getTime()
long milli = instant.toEpochMilli();
System.out.println(milli); //1589104867591
//ofEpochMilli():通过给定的毫秒数,获取Instant实例 -->Date(long millis)
Instant instant1 = Instant.ofEpochMilli(1550475314878L);
System.out.println(instant1); //2019-02-18T07:35:14.878Z
}
}
import org.junit.Test;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;
/**
* jdk 8中日期时间API的测试
*/
public class JDK8DateTimeTest {
/**
* DateTimeFormatter:格式化或解析日期、时间
* 类似于SimpleDateFormat
*/
@Test
public void test3(){
//方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
//格式化:日期-->字符串
LocalDateTime localDateTime = LocalDateTime.now();
String str1 = formatter.format(localDateTime);
System.out.println(localDateTime);
System.out.println(str1);//2020-05-10T18:26:40.234
//解析:字符串 -->日期
TemporalAccessor parse = formatter.parse("2020-05-10T18:26:40.234");
System.out.println(parse);
//方式二:
//本地化相关的格式。如:ofLocalizedDateTime()
//FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
//格式化
String str2 = formatter1.format(localDateTime);
System.out.println(str2);//2020年5月10日 下午06时26分40秒
//本地化相关的格式。如:ofLocalizedDate()
//FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
//格式化
String str3 = formatter2.format(LocalDate.now());
System.out.println(str3);//2020-5-10
//重点: 方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
//格式化
String str4 = formatter3.format(LocalDateTime.now());
System.out.println(str4);//2020-05-10 06:26:40
//解析
TemporalAccessor accessor = formatter3.parse("2020-05-10 06:26:40");
System.out.println(accessor);
}
}
import org.junit.Test;
import java.time.*;
import java.util.Set;
/**
* jdk 8中日期时间API的测试
*/
public class JDK8DateTimeTest {
@Test
public void test1(){
//ZoneId:类中包含了所有的时区信息
// ZoneId的getAvailableZoneIds():获取所有的ZoneId
Set<String> zoneIds= ZoneId.getAvailableZoneIds();
for(String s: zoneIds) {
System.out.println(s);
}
// ZoneId的of():获取指定时区的时间
LocalDateTime localDateTime= LocalDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println(localDateTime);
//ZonedDateTime:带时区的日期时间
// ZonedDateTime的now():获取本时区的ZonedDateTime对象
ZonedDateTime zonedDateTime= ZonedDateTime.now();
System.out.println(zonedDateTime);
// ZonedDateTime的now(ZoneId id):获取指定时区的ZonedDateTime对象
ZonedDateTime zonedDateTime1= ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
System.out.println(zonedDateTime1);
}
}
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import org.junit.Test;
public class JDK8APITest {
@Test
public void test2(){
//Duration:用于计算两个“时间”间隔,以秒和纳秒为基准
LocalTime localTime= LocalTime.now();
LocalTime localTime1= LocalTime.of(15, 23, 32);
//between():静态方法,返回Duration对象,表示两个时间的间隔
Duration duration= Duration.between(localTime1, localTime);
System.out.println(duration);
System.out.println(duration.getSeconds());
System.out.println(duration.getNano());
LocalDateTime localDateTime= LocalDateTime.of(2016, 6, 12, 15, 23, 32);
LocalDateTime localDateTime1= LocalDateTime.of(2017, 6, 12, 15, 23, 32);
Duration duration1= Duration.between(localDateTime1, localDateTime);
System.out.println(duration1.toDays());
}
}
import java.time.Period;
import org.junit.Test;
public class JDK8APITest {
@Test
public void test3(){
//Period:用于计算两个“日期”间隔,以年、月、日衡量
LocalDate localDate= LocalDate.now();
LocalDate localDate1= LocalDate.of(2028, 3, 18);
Period period= Period.between(localDate, localDate1);
System.out.println(period);
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());
Period period1= period.withYears(2);
System.out.println(period1);
}
}