在 Java 中创建日期的正确方法是什么? [英] What's the right way to create a date in Java?

查看:21
本文介绍了在 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 中创建日期的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆