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 中创建日期的正确方法是什么?


- 转换 ldap 日期 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 获取数字的最后一位 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01