在Java中创建日期和时间(不使用.now)。

huangapple go评论75阅读模式
英文:

Create a Date and Time in Java (not the .now)

问题

我目前需要创建自己的日期用户需要指定日期),但不是当前日期
我想要的日期格式符合 Joda Time 的规定DateTime(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute)

尽管任何替代方法都会有帮助
这是我的代码

```java
DateTime firstDate = new DateTime(2020,10,9,12,30);

<details>
<summary>英文:</summary>

I currently need to create my own dates (a user has to specify it), but it is not the current date.
I want in in the format specified in Joda Time. DateTime(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute)

Although any alternative will help.
This is my code:

```java
DateTime firstDate = new DateTime(2020,10,9,12,30);

答案1

得分: 3

你可以使用LocalDateTime,它是现代日期时间API的一部分。

import java.time.LocalDateTime;

public class Main {
    public static void main(String[] args) {
        LocalDateTime ldt = LocalDateTime.of(2020, 10, 9, 12, 30);
        System.out.println(ldt);
    }
}

输出:

2020-10-09T12:30

在**Trail: Date Time**中了解更多关于现代日期时间API的信息。

如建议此处,Joda-time除了保持时区数据最新外,已不再进行活跃开发。从Java SE 8开始,要求用户迁移到java.time(JSR-310)——JDK的核心部分,以取代该项目。

如果您在进行Android项目,并且您的Android API级别仍不符合Java-8,请查看通过desugaring使用Java 8+ API如何在Android项目中使用ThreeTenABP

英文:

You can use LocalDateTime which is part of the modern date-time API.

import java.time.LocalDateTime;

public class Main {
	public static void main(String[] args) {
		LocalDateTime ldt = LocalDateTime.of(2020, 10, 9, 12, 30);
		System.out.println(ldt);
	}
}

Output:

2020-10-09T12:30

Learn more about the modern date-time API at Trail: Date Time.

As suggested here, Joda-time is no longer in active development except to keep timezone data up to date. From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

If you are doing it for your Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

huangapple
  • 本文由 发表于 2020年10月10日 06:06:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64287907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定