JDK8的时间API怎么计算三天打渔,两天晒网,某一天在干什么的问题?

自己写了一个JDK8之前的,但是JDK8之后的不太懂。

package date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CheckWhatDoing {
    public static void main(String[] args) {
        String str = "1990-01-01";
//        JDK8之前
        String str1 = str + " 00:00:00";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date;
        try {
            date = simpleDateFormat.parse(str1);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        System.out.println(date);
        long time = date.getTime();
        Date now = new Date(90, 00, 03, 00, 00);
        System.out.println(now);
        long time1 = now.getTime();
        long s = time1 - time;
        System.out.println(s);
        double days = s / 1000/ 60.0 / 60 / 24 % 5;
        System.out.println(days);
        if(days < 5){
            if(days < 3){
                System.out.println("正在打渔");
            }else {
                System.out.println("正在晒网");
            }
        }
    }
}
java-8·java
189 views
Comments
登录后评论
Sign In
·

几个建议:

  • DateTimeFormatter(线程安全) 替换 SimpleDateFormat(线程不安全)
  • 使用 JDK11/JDK17版本,JDK8 已经 out 了,写法太啰嗦
  • 这个编辑器是可以语法高亮的,代码块旁边有个可以选择语言的 select,代码只有一个颜色看着难受
  • 代码风格(我强迫症):if else 语句和括号之间加入空格,可以使用 IDE 格式化代码
·

DateTimeFormatter (Java Platform SE 8 ) - Oracle Help Center

A formatter created from a pattern can be used as many times as necessary, it is immutable and is thread-safe.

·

看看 JDK 8 的 time 处理多舒服

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class CheckWhatDoing {
    public static void main(String[] args) {
        String str = "1990-01-01 00:00:00";
        LocalDateTime startDay = LocalDateTime.parse(str, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime now = LocalDateTime.now();
        int days = (int) Duration.between(startDay, now).toDays();
        System.out.println(days);
        if ((days % 5) < 3) {
            System.out.println("正在打渔");
        } else {
            System.out.println("正在晒网");
        }
    }