下个月的第一天使用 java Joda-Time

2023-02-09Java开发问题
9

本文介绍了下个月的第一天使用 java Joda-Time的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

你会如何用 org.joda.time 包重写下面的方法,它返回下个月的第一天/joda-time/" rel="noreferrer">Joda-Time?

How would you rewrite the method below, which returns the first day of next month, with the org.joda.time package in Joda-Time?

public static Date firstDayOfNextMonth() {
    Calendar nowCal = Calendar.getInstance();
    int month = nowCal.get(Calendar.MONTH) + 1;
    int year = nowCal.get(Calendar.YEAR);

    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month);
    cal.set(Calendar.DAY_OF_MONTH, 1);
    Date dueDate = new Date(cal.getTimeInMillis());

    return dueDate;
}

推荐答案

   LocalDate today = new LocalDate();
   LocalDate d1 = today.plusMonths(1).withDayOfMonth(1);

更容易和更清洁,不是吗?:-)

A little easier and cleaner, isn't it? :-)

更新:如果你想返回一个日期:

Update: If you want to return a date:

return new Date(d1.toDateTimeAtStartOfDay().getMillis());

但我强烈建议您避免将纯 DATE 类型(即日历中的一天,没有时间信息)与 DATETIME 类型混合,特别是与可怕的 java.util.Date 一样的物理"日期时间类型 .这有点像从整数和浮点类型转换,你必须小心.

but I strongly advise you to avoid mixing pure DATE types (i.e. a day in the calendar, without time information) with DATETIME types, specially with a "physical" datetime type as is the hideous java.util.Date . It's somewhat like converting from-to integer and floating types, you must be careful.

这篇关于下个月的第一天使用 java Joda-Time的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13