如何将一年中的几周转换为LocalDate

如何解决如何将一年中的几周转换为LocalDate

我都有一个字符串,例如年份和星期。 “ 2015-40”和年月格式,例如“ 2015-08”,它想在Scala中转换为LocalDate。

我尝试使用

val date = "2015-40"
val formatter = DateTimeFormatter.ofPattern("yyyy-ww") 
LocalDate.parse(date,formatter)

,但最终出现DateTimeParseException错误。希望对执行此操作有任何帮助

预先感谢

解决方法

    String date = "2015-40";
    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("YYYY-ww")
            .parseDefaulting(ChronoField.DAY_OF_WEEK,DayOfWeek.MONDAY.getValue())
            .toFormatter(Locale.FRANCE);
    LocalDate ld = LocalDate.parse(date,formatter);
    
    System.out.println(ld);

对不起,我只能写Java,我相信您可以将其翻译成Scala。输出为:

2015-09-28

您为什么要例外?我们缺少将2015-40解析为LocalDate的几件事:

  • LocalDate是一个日历日期,第40周由7天组成。 Java不知道您要在那7天中的哪几天去,因此拒绝为您做出选择。在上面的代码中,我指定了星期一。一周中的任何其他日子都可以。
  • 有点微妙。尽管对于人类来说,2015年和第40周是明确的,但新年前后并非总是如此,因为第1周可能在新年之前开始,或者第52或53周在新年之后开始。因此,日历年和星期数并不总是定义一个特定的星期。取而代之的是,我们需要周年基于周的年的概念。一周的年份从第1周开始(包括第1周),无论这意味着它在新年前后的几天开始。它持续到上周的最后一天,通常是在新年前后的几天。要告诉DateTimeFormatter我们要解析(或打印)一周的年份,我们需要使用大写的YYYY而不是小写的yyyy(或uuuu)。 / li>

顺便说一句,如果可以影响格式,请考虑将2015-W40W一起使用。这是年份和星期的ISO 8601格式。在ISO中,2015-12表示年份和月份,许多人会这样阅读。因此要消除歧义并避免误读。

编辑:

在我的解释中,我假设使用ISO周计划(星期一为一周的第一天,而第1周定义为新年中至少有4天的第一周)。您可以将不同的语言环境传递给格式化程序生成器,以获得不同的星期计划。

如果您确定自己的星期符合ISO标准,那么Andreas在评论中的建议就足够了,我们希望将其作为答案的一部分:

或者,添加ThreeTen Extra库,以便您可以使用 YearWeek 类,具有不错的atDay​(DayOfWeek dayOfWeek) LocalDate的获取方法。

链接: Wikipedia article: ISO 8601

,

LocalDate分为三个部分:年,月和月中的日。因此,对于year-month字符串,您将必须根据需要在特定的日期获取LocalDate。如演示代码所示,直接解析年月字符串。

对于year-week字符串,您将必须在一周的特定日期(例如,星期一或今天等。此外,与直接解析字符串相比,我发现更容易获取年份和星期,然后使用方法LocalDate获取所需的LocalDate实例。

LocalDate

输出:

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;

public class Main {
    public static void main(String[] args) {
        //#################### Year-Month #######################
        // Given year-month string
        var yearMonthStr = "2015-08";

        // LocalDate parsed from yearMonthStr and on the 1st day of the month
        LocalDate date2 = YearMonth.parse(yearMonthStr,DateTimeFormatter.ofPattern("u-M")).atDay(1);
        System.out.println(date2);

        // LocalDate parsed from yearMonthStr and on the last day of the month
        date2 = YearMonth.parse(yearMonthStr,DateTimeFormatter.ofPattern("u-M")).atEndOfMonth();
        System.out.println(date2);

        // LocalDate parsed from yearMonthStr and on specific day of the month
        date2 = YearMonth.parse(yearMonthStr,DateTimeFormatter.ofPattern("u-M")).atDay(1).withDayOfMonth(10);
        System.out.println(date2);

        
        //#################### Year-Week #######################
        // Given year-week string
        var yearWeekStr = "2015-40";

        // Split the string on '-' and get year and week values
        String[] parts = yearWeekStr.split("-");
        int year = Integer.parseInt(parts[0]);
        int week = Integer.parseInt(parts[1]);

        // LocalDate with year,week and today's day e.g. Fri
        LocalDate date1 = LocalDate.now()
                            .withYear(year)
                            .with(WeekFields.ISO.weekOfYear(),week);
        System.out.println(date1);

        // LocalDate with year,week and next Mon (or same if today is Mon)
        date1 = LocalDate.now()
                .withYear(year)
                .with(WeekFields.ISO.weekOfYear(),week)
                .with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
        System.out.println(date1);

        // LocalDate with year,week and today's day previous Mon (or same if today is Mon)
        date1 = LocalDate.now()
                .withYear(year)
                .with(WeekFields.ISO.weekOfYear(),week)
                .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        System.out.println(date1);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-