xiaojianbang
V2EX  ›  科技

请教关于 Java 日期转换的问题

  •  
  •   xiaojianbang · Oct 25, 2021 · 1978 views
    This topic created in 1686 days ago, the information mentioned may be changed or developed.

    请教大佬们一个关于 java 日期转换的一个问题;
    需求:提供一个时间戳,根据时间戳解析出年、月、半年、周、日;
    如果时间戳代表含义为月;
    a: 需要生成出当前时间戳所在月全部天数的时间戳,比如时间戳时间为 2021-10-01 ,则生成 10 月份全部 31 天(自动判断 28 、30 、31 天);
    b: 需要生成当前时间戳所在月处于第几周,并补全所在月全部的全部周期(如果:当前所在月为第 21 周、则补全这个月内的 22 、23 、24 周的时间戳)

    java 是否有关于两个日期内的相对增量计算 api 呢,或者有什么比较好用的日期库使用。

    5 replies    2021-10-25 23:23:20 +08:00
    yidinghe
        1
    yidinghe  
       Oct 25, 2021 via Android
    JDK 自带 API 足够了
    aguesuka
        3
    aguesuka  
       Oct 25, 2021
    import java.time.LocalDate;
    import java.time.YearMonth;
    import java.time.temporal.WeekFields;
    import java.util.List;
    import java.util.stream.IntStream;

    class Scratch {

    public static void main(String[] args) {
    // 问题 a, 需要生成出当前时间戳所在月全部天数的时间戳
    System.out.println(daysOfMonth(YearMonth.now()));
    // 问题 b 也许是个 XY 问题. 这里给出制定某天, 给出这天是第几周
    System.out.println(getISOWeekOfYear(LocalDate.now()));
    }

    public static List<LocalDate> daysOfMonth(YearMonth yearMonth) {
    return IntStream.rangeClosed(1, yearMonth.lengthOfMonth())
    .mapToObj(yearMonth::atDay)
    .toList();
    }

    public static int getISOWeekOfYear(LocalDate day) {
    return day.get(WeekFields.ISO.weekOfYear());
    }
    }
    wolfie
        4
    wolfie  
       Oct 25, 2021
    Hutool 用了就离不开
    xiaojianbang
        5
    xiaojianbang  
    OP
       Oct 25, 2021
    @aguesuka @lack006 @wolfie @yidinghe 感谢感谢,明天我去研究下
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2798 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 12:15 · PVG 20:15 · LAX 05:15 · JFK 08:15
    ♥ Do have faith in what you're doing.