返回顶部

Java常见知识积累

1.计算两个日期时间差

public static String getDatePoor(Date endDate, Date nowDate) {
 
    long nd = 1000 * 24 * 60 * 60;
    long nh = 1000 * 60 * 60;
    long nm = 1000 * 60;
    // long ns = 1000;
    // 获得两个时间的毫秒时间差异
    long diff = endDate.getTime() - nowDate.getTime();
    // 计算差多少天
    long day = diff / nd;
    // 计算差多少小时
    long hour = diff % nd / nh;
    // 计算差多少分钟
    long min = diff % nd % nh / nm;
    // 计算差多少秒//输出结果
    // long sec = diff % nd % nh % nm / ns;
    return day + "天" + hour + "小时" + min + "分钟";
}

 

2.日期转字符串

public static String DateToStr(Date date) {
      
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String str = format.format(date);
    return str;
}

 

3.字符串转日期

public static Date StrToDate(String str) {

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = null;
    try {
        date = format.parse(str);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

 

4.SQL日期转字符串:
select to_char(sysdate,'yyyy-MM-dd HH24:mi:ss') from dual;
SQL字符串转日期:
select to_date('2005-01-01 13:14:20','yyyy-MM-dd HH24:mi:ss') from dual;

 

5.Java 8 Stream

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

forEach

Random random = new Random();

random.ints().limit(10).forEach(System.out::println);

map

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

// 获取对应的平方数

List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

filter

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");

// 获取空字符串的数量

long count = strings.stream().filter(string -> string.isEmpty()).count();

limit

Random random = new Random();

random.ints().limit(10).forEach(System.out::println);

sorted

Random random = new Random();

random.ints().limit(10).sorted().forEach(System.out::println);

并行(parallel)程序

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");

// 获取空字符串的数量

long count = strings.parallelStream().filter(string -> string.isEmpty()).count();

Collectors

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");

List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

System.out.println("筛选列表: " + filtered);

String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));

System.out.println("合并字符串: " + mergedString);

posted @ 2020-12-25 21:32  不懒人  阅读(121)  评论(0编辑  收藏  举报