V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
xiaojianbang
V2EX  ›  科技

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

  •  
  •   xiaojianbang · 2021-10-25 17:59:34 +08:00 · 840 次点击
    这是一个创建于 885 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    5 条回复    2021-10-25 23:23:20 +08:00
    yidinghe
        1
    yidinghe  
       2021-10-25 18:00:45 +08:00 via Android
    JDK 自带 API 足够了
    aguesuka
        3
    aguesuka  
       2021-10-25 18:41:32 +08:00
    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  
       2021-10-25 18:48:08 +08:00
    Hutool 用了就离不开
    xiaojianbang
        5
    xiaojianbang  
    OP
       2021-10-25 23:23:20 +08:00
    @aguesuka @lack006 @wolfie @yidinghe 感谢感谢,明天我去研究下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1004 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 22:18 · PVG 06:18 · LAX 15:18 · JFK 18:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.