Java 日期与日历 [英] Java Date vs Calendar

查看:30
本文介绍了Java 日期与日历的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以建议当前关于 DateCalendar 类型的最佳实践".

Could someone please advise the current "best practice" around Date and Calendar types.

在编写新代码时,最好总是使用 Calendar 而不是 Date,或者在某些情况下 Date 是更合适的数据类型?

When writing new code, is it best to always favour Calendar over Date, or are there circumstances where Date is the more appropriate datatype?

推荐答案

Date 是一个更简单的类,主要是出于向后兼容性的原因.如果您需要设置特定日期或进行日期算术,请使用日历.日历还处理本地化.Date 之前的日期操作功能已被弃用.

Date is a simpler class and is mainly there for backward compatibility reasons. If you need to set particular dates or do date arithmetic, use a Calendar. Calendars also handle localization. The previous date manipulation functions of Date have since been deprecated.

我个人倾向于在有选择时使用以毫秒为单位的时间作为长(或长,视情况而定)或日历.

Personally I tend to use either time in milliseconds as a long (or Long, as appropriate) or Calendar when there is a choice.

日期和日历都是可变的,这在 API 中使用时往往会出现问题.

Both Date and Calendar are mutable, which tends to present issues when using either in an API.

这篇关于Java 日期与日历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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