百味皆苦 java后端开发攻城狮

java8新特性

2019-10-13
百味皆苦

Lambda 表达式

  • Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性。

  • Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。

  • Lambda表达式是一种匿名函数,它没有声明的方法,即没有访问修饰符,返回值声明和名字

  • 一个Lambda表达式可以有零个或多个参数

    参数的类型既可以明确声明,也可以根据上下文推断,例如:(int a)和(a)效果相同

    所有参数需要包含在圆括号内,参数之间用逗号相隔。例如:(a,b)或(int a,int b)

    空圆括号代表参数集为空。() -> 42

    当只有一个参数,且其类型可以推导时,圆括号可以省略a -> return a*a

    Lambda表达式的主体可包含零条或多条语句

    如果Lambda表达式的主体只有一条语句,花括号可省略。匿名函数的返回类型与该主体表达式一致

    如果Lambda表达式的主体包含一条以上语句,则表达式必须包含在花括号中。匿名函数的返回类型与代码块的返回类型一致,若没有返回则为空

  • 特征:

  • 可选类型声明:不需要声明参数类型,编译器可以统一识别参数值。
  • 可选的参数圆括号:一个参数无需定义圆括号,但多个参数需要定义圆括号
  • 可选的大括号:如果主体包含了一个语句,就不需要使用大括号。
  • 可选的返回关键字:如果主体只有一个表达式返回值则编译器会自动返回值,大括号需要指定明表达式返回了一个数值。

  • Lambda 表达式需要注意以下两点:

    Lambda 表达式主要用来定义行内执行的方法类型接口

    Lambda 表达式免去了使用匿名方法的麻烦

语法格式

(parameters) -> expression

(parameters) ->{ statements; }
// 1. 不需要参数,返回值为 5  
() -> 5  
  
// 2. 接收一个参数(数字类型),返回其2倍的值  
x -> 2 * x  
  
// 3. 接受2个参数(数字),并返回他们的差值  
(x, y) -> x  y  
  
// 4. 接收2个int型整数,返回他们的和  
(int x, int y) -> x + y  
  
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)  
(String s) -> System.out.print(s)
public class Java8Tester {
   public static void main(String args[]){
      Java8Tester tester = new Java8Tester();
        
      // 类型声明
      MathOperation addition = (int a, int b) -> a + b;
        
      // 不用类型声明
      MathOperation subtraction = (a, b) -> a - b;
        
      // 大括号中的返回语句
      MathOperation multiplication = (int a, int b) -> { return a * b; };
        
      // 没有大括号及返回语句
      MathOperation division = (int a, int b) -> a / b;
        
      System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
      System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
      System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
      System.out.println("10 / 5 = " + tester.operate(10, 5, division));
        
      // 不用括号
      GreetingService greetService1 = message ->
      System.out.println("Hello " + message);
        
      // 用括号
      GreetingService greetService2 = (message) ->
      System.out.println("Hello " + message);
        
      greetService1.sayMessage("Runoob");
      greetService2.sayMessage("Google");
      
   }
    
   interface MathOperation {
      int operation(int a, int b);
   }
    
   interface GreetingService {
      void sayMessage(String message);
   }
    
   private int operate(int a, int b, MathOperation mathOperation){
      return mathOperation.operation(a, b);
   }
}
/*
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Runoob
Hello Google
*/

函数式接口

  • 如果一个接口只有一个抽象方法,那么该接口就是一个函数式接口
  • 如果在某个接口上声明了一个FunctionalInterface注解,那么编译器就会按照函数式接口的定义来要求该接口
  • 如果某个接口只有一个抽象方法,但我们并没有给该接口声明FunctionalInterface注解,那么编译器依旧会将该接口看做是函数式接口

  • 在将函数作为一等公民的语言中,lambda表达式的类型是函数(比如JavaScript),但在java中,lambda表达式是对象,他们必须依赖于一类特别的对象类型:函数式接口(functional interface)。
//遍历集合
List<Integer> list = Arrays.asList(1,2,3,4,5);
list.forEach(i -> {
    System.out.println(i);
});
//方法引用:method reference
list.forEach(System.out::println);
//-------------------------------------------
List<String> list2 = Arrays.asList("str","hello");
//存放list中元素转换为大写后的集合
List<String> res = new ArrayList<>();
list2.forEach((item) -> {res.add(item.toUpperCase())});
//使用stream流操作
list.stream().map(item -> item.toUpperCase()).forEach(item ->System.out.println(item));
//使用方法引用
list.stream().map(String::toUpperCase()).forEach(item ->System.out.println(item));
//排序
Collections.sort(list2, (o1,o2) -> 02.compateTo(o1));

//建立线程
new Thread(() -> {System.out.println("run方法实现");}).start();

Function接口

  • Lambda表达式其实是向Function接口传递的一个行为,而不是一个参数
  • 这个接口的apply方法只有一个输入参数和一个返回值
//原始方法
public int method1(int a){
    //2*a其实就是一种行为
    return 2*a;
}
public int method2(int a) {
    return 5+a;
}
System.out.println(method1(2))//结果为:4
System.out.println(method2(2))//结果为:7
    
//使用Lambda方式传递行为
//Function<Integer,Integer>表示传入一个Integer类型,返回一个Integer类型
public int compute(int a,Function<Integer,Integer>function){
    int result = function.apply(a);
    return result;
}
//Function传入一个Integer类型,返回一个String类型
public String conver(int a, Function<Integer,String>function){
    return function.apply(a);
}
//传递的行为是:2*value
System.out.println(compute(2,value -> {2*value}));//结果:4
//传递的行为是:value + " hello"
System.out.println(conver(2,value -> {String.valueOf(value + " hello")}));
compose和andThen
  • 这两个方法是Function接口中的两个默认方法
public int compute(int a, Function<Integer,Integer> fun1,Function<Integer,Integer> fun2)
{
    //compose方法先执行参数的function中的apply,然后再执行自己的apply方法
    return fun1.compose(fun2).apply(a);
}
public int compute2(int a, Function<Integer,Integer> fun1,Function<Integer,Integer> fun2)
{
    //andThen方法先执行自己的apply方法,然后执行参数中的function的apply方法
    return fun1.andThen(fun2).apply(a);
}
//结果为:12。先执行参数function的行为2*2=4,然后执行自己的行为4*3=12
System.out.println(comupute(2, value -> value * 3, value -> value * value))
//结果为:36,先执行自己的行为2*3=6,然后执行参数function的行为6*6=36
System.out.println(comupute2(2, value -> value * 3, value -> value * value))

BiFunction接口

  • 与Function接口的区别是apply方法有两个输入参数和一个返回值
  • 只有一个andThen默认方法
public int compute(int a,int b,Function<Integer,Integer,Integer>function){
    int result = function.apply(a,b);
    return result;
}
System.out.println(compute(2,3,(value1,value2) -> {value1*value2}));//结果:6


public int compute2(int a,int b,BiFunction<Integer,Integer,Integer>bifun,
                  Function<Integer,Integer> fun){
    return bifun.andThen(fun).apply(a,b);
}
//结果:25
System.out.println(compute2(2,3,(value1,value2) -> {value1+value2},val -> val*val));
public List<Person> getPersonByUsername(String username,List<Person> persons)
{
    return persons.stream().filter(person -> person.getUsername().equals(username)).
        collect(Collections.toList());
}
public List<Person> getPersonByAge(int age,List<Person> persons)
{
    BiFunction<Integer,List<Person>,List<Person>> bi = (ageOfPerson,personList) ->
        return personList.stream().filter(person -> person.getAge() > ageOfPerson).collect(Collections.toList());
    return bi.apply(age,persons);
}
//更加灵活,由调用者根据参数制定行为
public List<Person> getPersonByAge2(int age,List<Person> persons,BiFunction<Integer,List<person>> biFunction)
{
    return biFunction.apply(age,persons);
}

Person person1 = new Person("zhangsan",22);
Person person2= new Person("lisi",25);
Person person3 = new Person("wangwu",33);
List<Person> persons = Arrays.asList(person1,person2,person3);
//从list集合中查找名字匹配的对象重新封装为一个集合
List<Person> personResult = xxx.getPersonByUsername("zhagnsan",persons);
personResult.forEach(person -> System.out.println(person.getUsername()));

//从list集合中查找年龄在范围内的对象重新封装为一个集合
List<Person> personResult2 = xxx.getPersonByAge(20,persons);
personResult.forEach(person -> System.out.println(person.getAge()));
//由调用者制定行为
List<Person> personResult3 = xxx.getgetPersonByAge2(20,persons,(age,personList) -> {
    return personList.stream().filter(person -> person.getAge() >= age).collect(Collections.toList());
});

Predicate接口

  • 提供了一个test方法,判断参数是否满足一定条件,返回一个boolean值
public void condition(List<Integer> list, Predicate<Integer> pre) {
    for(Integer integer : list) {
        if(pre.test(integer))
            Syetem.out.println(integer);
    }
}

List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9);
//找出大于3的数
xxx.condition(list,item -> item > 3);
//打印全部
xxx.condition(list,item -> true);
与、或、非
  • 与操作:默认方法and()
  • 或操作:默认方法or()
  • 取反操作:negate()
public void condition(List<Integer> list, Predicate<Integer> pre1,Predicate<Integer> pre2) {
    for(Integer integer : list) {
        if(pre1.and(pre2).test(integer))
            Syetem.out.println(integer);
    }
}
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9);
//输出大于5并且是偶数的数
xxx.condition(list,item -> item > 5,item -> item % 2 == 0);

Supplier接口

  • 不接收参数,返回一个结果
//不传入参数,返回一个Student类型,调用无参构造方法
Supplier<Student> supplier = Student :: new;
System.out.println(supplier.get().getName());

//比较方法
public String getSort(String a,String b,Comparator<String> comparator){
    return BinaryOperator.maxBy(comparator).apply(a,b);
}
xxx.getSort("hello","world",(a,b) -> a.length() - b.length());
方法引用
  • 方法引用通过方法的名字来指向一个方法。
  • 方法引用使用一对冒号 ::
@FunctionalInterface
public interface Supplier<T> {
    T get();
}
 
class Car {
    //Supplier是jdk1.8的接口,这里和lamda一起使用了
    public static Car create(final Supplier<Car> supplier) {
        return supplier.get();
    }
 
    public static void collide(final Car car) {
        System.out.println("Collided " + car.toString());
    }
 
    public void follow(final Car another) {
        System.out.println("Following the " + another.toString());
    }
 
    public void repair() {
        System.out.println("Repaired " + this.toString());
    }
}

//构造器引用:它的语法是Class::new,或者更一般的Class< T >::new实例如下:
final Car car = Car.create( Car::new );
final List< Car > cars = Arrays.asList( car );
//静态方法引用:它的语法是Class::static_method,实例如下:
cars.forEach( Car::collide );
//特定类的任意对象的方法引用:它的语法是Class::method实例如下:
cars.forEach( Car::repair );
//特定对象的方法引用:它的语法是instance::method实例如下:
final Car police = Car.create( Car::new );
cars.forEach( police::follow );

Optional类处理NPE

  • Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。
  • Optional 是个容器:它可以保存类型T的值,或者仅仅保存null。
  • Optional 类的引入很好的解决空指针异常。
public class Java8Tester {
   public static void main(String args[]){
   
      Java8Tester java8Tester = new Java8Tester();
      Integer value1 = null;
      Integer value2 = new Integer(10);
        
      // Optional.ofNullable - 允许传递为 null 参数
      Optional<Integer> a = Optional.ofNullable(value1);
        
      // Optional.of - 如果传递的参数是 null,抛出异常 NullPointerException
      Optional<Integer> b = Optional.of(value2);
      System.out.println(java8Tester.sum(a,b));
   }
    
   public Integer sum(Optional<Integer> a, Optional<Integer> b){
    
      // Optional.isPresent - 判断值是否存在
        
      System.out.println("第一个参数值存在: " + a.isPresent());
      System.out.println("第二个参数值存在: " + b.isPresent());
        
      // Optional.orElse - 如果值存在,返回它,否则返回默认值
      Integer value1 = a.orElse(new Integer(0));
        
      //Optional.get - 获取值,值需要存在
      Integer value2 = b.get();
      return value1 + value2;
   }
}
/*
第一个参数值存在: false
第二个参数值存在: true
10
*/
Employee employee = new Employee();
employee.setName("zhangsan");
Employee employee2 = new Employee();
employee2.setName("lisi");
Company company = new Company();
company.setName("company1");

List<Employee> employees = Arrays.asList(employee, employee2);
company.setEmployees(employees);

List<Employee> list = company.getEmployees();
//创建一个容器
Optional<Company> optional = Optional.ofNullable(company);
//如果list集合不为空则返回,如果list集合为null,返回一个空集合
System.out.println(optional.map(theCompany -> theCompany.getEmployees()).
                   orElse(Collections.emptyList()));

stream流

  • Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。

  • 这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。

  • 元素流在管道中经过中间操作(intermediate operation)的处理,最后由最终操作(terminal operation)得到前面处理的结果。

  • Stream(流)是一个来自数据源的元素队列并支持聚合操作

    • 元素是特定类型的对象,形成一个队列。 Java中的Stream并不会存储元素,而是按需计算。
    • 数据源: 流的来源。 可以是集合,数组,I/O channel, 产生器generator 等。
    • 聚合操作: 类似SQL语句一样的操作, 比如filter, map, reduce, find, match, sorted等。
  • Stream操作还有两个基础的特征:

  • Pipelining: 中间操作都会返回流对象本身。 这样多个操作可以串联成一个管道, 如同流式风格(fluent style)。

  • 内部迭代: 以前对集合遍历都是通过Iterator或者For-Each的方式, 显式的在集合外部进行迭代, 这叫做外部迭代。 Stream提供了内部迭代的方式, 通过访问者模式(Visitor)实现。

  • 流的构成:源,零个或多个中间操作,终止操作。
  • 流操作的分类:惰性求值,及早求值。
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
//对集合中的元素进行乘2然后相加
System.out.println(list.stream().map(i -> 2*i).reduce(0,Integer::sum));

//把流转换为数组
Stream<String> stream = Stream.of("hello","world");
String[] strArray = stream.toArray(length -> new String(length));
String[] strArray = stream.toArray(String[]::new);//方法引用形式

//流转换为集合
Stream<String> stream = Stream.of("hello","world");
List<String> list = stream.collect(Collections.toList());
//复杂方法
List<String> list = stream.collect(() -> new ArrayList(), (theList,item) -> theList.add(item), (theList1,theList2) -> theList1.addAll(theList2));
//使用方法引用
List<String> list = stream.collect(LinkedList::new, LinkedList::add, LinkedList::addAll);

//转换为各种集合
Stream<String> stream = Stream.of("hello", "world", "helloworld");
List<String> list = stream.collect(Collectors.toCollection(ArrayList::new));
Set<String> set = stream.collect(Collectors.toCollection(TreeSet::new));

//字符串连接
Stream<String> stream = Stream.of("hello", "world", "helloworld");
String str = stream.collect(Collectors.joining()).toString();

//把每个字符串转换为大写转为list集合输出
List<String> list = Arrays.asList("hello", "world", "helloworld", "test");
list.stream().map(String::toUpperCase).collect(Collectors.toList()).forEach(System.out::println);

//把多个list中的元素全部取出来放到一个list中
Stream<List<Integer>> stream = Stream.of(Arrays.asList(1),
                Arrays.asList(2, 3), Arrays.asList(4, 5, 6));
stream.flatMap(theList -> theList.stream()).map(item -> item * item)

//获取生成的第一个UUID字符串
Stream<String> stream = Stream.generate(UUID.randomUUID()::toString);
stream.findFirst().ifPresent(System.out::println);

//初始值为1,以后每个值在前一个基础上加2,共生成6个数
Stream<Integer> stream = Stream.iterate(1, item -> item + 2).limit(6);
//对生成的六个数先过滤,取大于2的所有数,然后把每个数映射成int类型的2倍,然后忽略前两个数,然后取前两个数求和
System.out.println(stream.filter(item -> item > 2).mapToInt(item -> item * 2).skip(2).limit(2).sum());
//使用summaryStatistics求和,最大值,最小值
IntSummaryStatistics summaryStatistics = stream.filter(item -> item > 2).mapToInt(item -> item * 2).skip(2).limit(2).summaryStatistics();
System.out.println(summaryStatistics.getMin());
System.out.println(summaryStatistics.getCount());
System.out.println(summaryStatistics.getMax());

//0和1去重
IntStream.iterate(0, i -> (i + 1) % 2).limit(6).distinct().forEach(System.out::println);

//排序
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
list.stream.sorted().forEach(System.out::println);

//获取长度为5的字符串,获取第一个,如果存在就打印不存在不做任何操作
List<String> list = Arrays.asList("hello", "world", "hello world");
list.stream().mapToInt(item -> item.length()).filter(length -> length == 5).
findFirst().ifPresent(System.out::println);

//对每个字符串根据空格切割,然后合并为一个流,进行去重,最后转换为一个list集合
List<String> list = Arrays.asList("hello welcome", "world hello",
                "hello world hello", "hello welcome");
List<String> result = list.stream().map(item -> item.split(" ")).flatMap(Arrays::stream).distinct().collect(Collectors.toList());

//交替组合{“Hi zhangsan”,“Hi lisi”。。。。}
List<String> list1 = Arrays.asList("Hi", "Hello", "你好");
List<String> list2 = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu");
List<String> result = list1.stream().flatMap(item -> list2.stream().map(item2 -> item + " " + item2)).collect(Collectors.toList());

Student student1 = new Student("zhangsan", 100, 20);
Student student2 = new Student("lisi", 90, 20);
Student student3 = new Student("wangwu", 90, 30);
Student student4 = new Student("zhangsan", 80, 40);
List<Student> students = Arrays.asList(student1, student2, student3, student4);
List<Student> students = Arrays.asList(student1, student2, student3, student4);
//根据成绩分组,分组的key是依据按什么分组决定的
Map<Integer, List<Student>> map = students.stream().collect(Collectors.groupingBy(Student::getScore));
//根据姓名分组,统计组中的数据个数
Map<String, Long> map = students.stream().
                collect(Collectors.groupingBy(Student::getName, Collectors.counting()));
//根据姓名分组,统计组中的分数平均值
Map<String, Double> map = students.stream().collect(Collectors.groupingBy(Student::getName, Collectors.averagingDouble(Student::getScore)));
//分区
Map<Boolean, List<Student>> map = students.stream().
    collect(Collectors.partitioningBy(student -> student.getScore() >= 90));

collect收集器

  • Collector作为collect方法的参数

    • Collector是一个接口,它是一个可变的汇聚操作,将输入元素累积到一个可变的结果容器中;它会在所有元素都处理完毕后,将累积的结果转换为一个最终的表示(这是一个可选操作),它支持串行与并行两种方式执行。

    • Collectors本身提供了关于关于Collector的常见汇聚实现,Collectors本身是一个工厂。
    • 为了确保串行与并行操作结果的等价性,Collector函数需要满足两个条件:identity(同一性)与associativity(结合性)。
Student student1 = new Student("zhangsan", 80);
Student student2 = new Student("lisi", 90);
Student student3 = new Student("wangwu", 100);
Student student4 = new Student("zhaoliu", 90);
Student student5 = new Student("zhaoliu", 90);
List<Student> students = Arrays.asList(student1, student2, student3, student4, student5);
//获取成绩为最小值的数据
students.stream().collect(minBy(Comparator.comparingInt(Student::getScore))).ifPresent(System.out::println);
//获取成绩为最大值的数据
students.stream().collect(maxBy(Comparator.comparingInt(Student::getScore))).ifPresent(System.out::println);
students.stream().collect(averagingInt(Student::getScore));//求平均值
students.stream().collect(summingInt(Student::getScore));//求和
//包含最大值,最小值,和,平均值和统计信息
IntSummaryStatistics intSummaryStatistics = students.stream().collect(summarizingInt(Student::getScore));
System.out.println(intSummaryStatistics);
//把所有姓名连接起来
students.stream().map(Student::getName).collect(joining());
System.out.println(students.stream().map(Student::getName).collect(joining(", ")));
//先根据成绩分组,然后根据姓名再分组
Map<Integer, Map<String, List<Student>>> map = students.stream().
                collect(groupingBy(Student::getScore, groupingBy(Student::getName)));
//根据成绩分区
Map<Boolean, List<Student>> map2 = students.stream().
                collect(partitioningBy(student -> student.getScore() > 80));
//根据成绩进行两次分区
Map<Boolean, Map<Boolean, List<Student>>> map3 = students.stream().
                collect(partitioningBy(student -> student.getScore() > 80, partitioningBy(student -> student.getScore() > 90)));
//统计分区结果
Map<Boolean, Long> map4 = students.stream().
                collect(partitioningBy(student -> student.getScore() > 80, counting()));
//根据姓名分组,找出分组后成绩最低的用户信息
Map<String, Student> map5 = students.stream().
                collect(groupingBy(Student::getName, collectingAndThen(minBy(Comparator.comparingInt(Student::getScore)),
                        Optional::get)));

joda时间处理

//获取当前日期时间
LocalDate localDate = LocalDate.now();
LocalDate localDate5 = LocalDate.now();
LocalDate localDate6 = LocalDate.of(2017, 3, 18);
System.out.println(localDate5.isAfter(localDate6));
System.out.println(localDate5.isBefore(localDate6));
System.out.println(localDate5.equals(localDate6));
//获取当前年,月,一个月中的第几天
System.out.println(localDate.getYear() + ", " + localDate.getMonthValue() + ", " + localDate.getDayOfMonth());

//自定义日期时间
LocalDate localDate2 = LocalDate.of(2017, 3, 3);

//设置当前日期的后第三个月的日为月初一
localDate = localDate.plusMonths(3).dayOfMonth().withMinimumValue();

//获取当前时间
LocalTime time = LocalTime.now();
//获取当前时间的后3小时20分钟
LocalTime time2 = time.plusHours(3).plusMinutes(20);
//获取当前日期的后两个星期
LocalDate localDate1 = localDate.plus(2, ChronoUnit.WEEKS);
//获取当前日期的前两星期
LocalDate localDate4 = localDate.minus(2, ChronoUnit.MONTHS);

//获取时区的时钟
Clock clock = Clock.systemDefaultZone();

//获取年月
YearMonth yearMonth = YearMonth.now();
System.out.println(yearMonth);
System.out.println(yearMonth.lengthOfMonth());
System.out.println(yearMonth.isLeapYear());

//获取两个日期的时间差
LocalDate localDate7 = LocalDate.now();
LocalDate localDate8 = LocalDate.of(2018, 3, 16);
Period period = Period.between(localDate7, localDate8);
System.out.println(period.getYears());
System.out.println(period.getMonths());
System.out.println(period.getDays());
//获取当前日期和后一天的日期
DateTime today = new DateTime();
DateTime tomorrow = today.plusDays(1);
System.out.println(today.toString("yyyy-MM-dd"));
System.out.println(tomorrow.toString("yyyy-MM-dd"));

//设置当前日期为这个月的第一天
DateTime d1 = today.withDayOfMonth(1);

// 计算2年前第3个月最后1天的日期
DateTime dateTime = new DateTime();
DateTime dateTime2 = dateTime.minusYears(2).monthOfYear().
    setCopy(3).dayOfMonth().withMinimumValue();
public class JodaTest3 {

    // 标准UTC时间:2014-11-04T09:22:54.876Z
    public static Date convertUTC2Date(String utcDate) {
        try {
            DateTime dateTime = DateTime.parse(utcDate, DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
            return dateTime.toDate();
        } catch (Exception ex) {
            return null;
        }
    }

    public static String convertDate2UTC(Date javaDate) {
        DateTime dateTime = new DateTime(javaDate, DateTimeZone.UTC);
        return dateTime.toString();
    }

    public static String convertDate2LocalByDateFormat(Date javaDate, String dateFormat) {
        DateTime dateTime = new DateTime(javaDate);
        return dateTime.toString(dateFormat);
    }

    public static void main(String[] args) {
        System.out.println(JodaTest3.convertUTC2Date("2014-11-04T09:22:54.876Z"));
        System.out.println(JodaTest3.convertDate2UTC(new Date()));
        System.out.println(JodaTest3.convertDate2LocalByDateFormat(new Date(), "yyyy-MM-dd HH:mm:ss"));
    }

}
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.LocalDateTime;
import java.time.Month;
 
public class Java8Tester {
   public static void main(String args[]){
      Java8Tester java8tester = new Java8Tester();
      java8tester.testLocalDateTime();
   }
    
   public void testLocalDateTime(){
    
      // 获取当前的日期时间
      LocalDateTime currentTime = LocalDateTime.now();
      System.out.println("当前时间: " + currentTime);
       //当前时间: 2016-04-15T16:55:48.668
        
      LocalDate date1 = currentTime.toLocalDate();
      System.out.println("date1: " + date1);
       //date1: 2016-04-15
        
      Month month = currentTime.getMonth();
      int day = currentTime.getDayOfMonth();
      int seconds = currentTime.getSecond();
        
      System.out.println("月: " + month +", 日: " + day +", 秒: " + seconds);
      // 月: APRIL, 日: 15, 秒: 48
        
      LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);
      System.out.println("date2: " + date2);
       //date2: 2012-04-10T16:55:48.668
        
      // 12 december 2014
      LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12);
      System.out.println("date3: " + date3);
       //date3: 2014-12-12
        
      // 22 小时 15 分钟
      LocalTime date4 = LocalTime.of(22, 15);
      System.out.println("date4: " + date4);
       //date4: 22:15
        
      // 解析字符串
      LocalTime date5 = LocalTime.parse("20:15:30");
      System.out.println("date5: " + date5);
      // date5: 20:15:30
   }
}
import java.time.ZonedDateTime;
import java.time.ZoneId;
 
public class Java8Tester {
   public static void main(String args[]){
      Java8Tester java8tester = new Java8Tester();
      java8tester.testZonedDateTime();
   }
    
   public void testZonedDateTime(){
    
      // 获取当前时间日期
      ZonedDateTime date1 = ZonedDateTime.parse("2015-12-03T10:15:30+05:30[Asia/Shanghai]");
      System.out.println("date1: " + date1);
       //date1: 2015-12-03T10:15:30+08:00[Asia/Shanghai]
        
      ZoneId id = ZoneId.of("Europe/Paris");
      System.out.println("ZoneId: " + id);
       //ZoneId: Europe/Paris
        
      ZoneId currentZone = ZoneId.systemDefault();
      System.out.println("当期时区: " + currentZone);
       //当期时区: Asia/Shanghai
   }
}

下一篇 java8实战

Comments

Content