What#39;s the right way to create a date in Java?(在 Java 中创建日期的正确方法是什么?)
问题描述
我对 Date 类的 Java API 感到困惑.一切似乎都已被弃用,并链接到 Calendar 类.所以我开始使用 Calendar 对象来做我希望用 Date 来做的事情,但直觉上,当我真正想做的只是创建和比较两个日期时,使用 Calendar 对象有点困扰我.
I get confused by the Java API for the Date class. Everything seems to be deprecated and links to the Calendar class. So I started using the Calendar objects to do what I would have liked to do with a Date, but intuitively it kind of bothers me to use a Calendar object when all I really want to do is create and compare two dates.
有没有简单的方法来做到这一点?现在我愿意
Is there a simple way to do that? For now I do
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day, hour, minute, second);
Date date = cal.getTime(); // get back a Date object
推荐答案
你可以使用SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");
但我不知道它是否应该被认为比使用日历更正确 ...
But I don't know whether it should be considered more right than to use Calendar ...
这篇关于在 Java 中创建日期的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中创建日期的正确方法是什么?


基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01