时间 vs 日期 vs 日历 java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12334972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:28:06  来源:igfitidea点击:

time vs date vs calendar java

javaandroiddatetimecalendar

提问by ghostrider

Well in my app I want to get current date and month abnd local hour (currentTimeZone hour) and depending on its value display some things.

那么在我的应用程序中,我想获取当前日期和月份和本地小时(currentTimeZone 小时)并根据其值显示一些内容。

i have read several sollutions and I have used the following:

我已经阅读了几个解决方案,并使用了以下内容:

Calendar c = Calendar.getInstance(); 
            int day=c.get(Calendar.DATE);
            int month=c.get(Calendar.MONTH);

or this

或这个

Time today = new Time(Time.getCurrentTimezone());
            today.setToNow();
            int day2=today.monthDay;
            int month2=today.month;

my questions are:

我的问题是:

1)which of this is more "Stable" considering their results? I mean that it will not have any problem.

1)考虑到他们的结果,哪个更“稳定”?我的意思是它不会有任何问题。

2)Moreover, did they both take into consideration the TimeZone? I think that the second one does, but what about the calendar?

2)此外,他们都考虑了时区吗?我认为第二个可以,但是日历呢?

3)I tried this code that I have found:

3)我尝试了我发现的这段代码:

SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
            String format = s.format(new Date());

and i get the error that Date() must have an argument. weird because in every answer they use it like that.

我得到 Date() 必须有一个参数的错误。很奇怪,因为在每个答案中,他们都是这样使用的。

What is wrong?

怎么了?

4) What do you suggest me to use? The only thing I want is a simple comparison between current month,date,hour with some stored in memory. (for example if its January 29, display that event. if it is 19.00 am send notification and so on.)

4)你建议我使用什么?我唯一想要的是当前月份、日期、小时与内存中存储的一些之间的简单比较。(例如,如果是 1 月 29 日,则显示该事件。如果是上午 19 点,则发送通知等。)

回答by Jo?o Silva

1) Which of this is more "Stable" considering their results? I mean that it will not have any problem.

1)考虑到他们的结果,哪个更“稳定”?我的意思是它不会有任何问题

They are both stable and very well tested, especially Calendarwhich is in the Java API since JDK1.1. Also from the docsof Time:

它们既稳定又经过很好的测试,尤其Calendar是自 JDK1.1 以来的 Java API 中。还从文档Time

An alternative to the Calendar and GregorianCalendar classes. An instance of the Time class represents a moment in time, specified with second precision. It is modelled after struct tm, and in fact, uses struct tm to implement most of the functionality.

Calendar 和 GregorianCalendar 类的替代品。Time 类的实例表示以秒精度指定的时刻。它是仿照struct tm 建模的,实际上使用struct tm 来实现大部分功能。

Time, imho, is much easier to work than Calendarthough.

Time,恕我直言,工作比Calendar虽然容易得多。

2) Moreover, did they both take into consideration the TimeZone? I think that the second one does, but what about the calendar?

2)此外,他们是否都考虑了时区?我认为第二个可以,但是日历呢?

Yes, they do. You can specify a TimeZoneusing Calendar.getInstance(java.util.TimeZone). Otherwise, a default one will be used.

是的,他们这样做。您可以指定一个TimeZoneusing Calendar.getInstance(java.util.TimeZone)。否则,将使用默认值。

3) I tried this code that I have found:

3)我尝试了我发现的这段代码:

The code works just fine. Make sure you are using new java.util.Date()instead of java.sql.Date, for example.

代码工作得很好。例如,确保您使用的是new java.util.Date()代替java.sql.Date

4) What do you suggest me to use? The only thing I want is a simple comparison between current month,date,hour with some stored in memory. (for example if its January 29, display that event. if it is 19.00 am send notification and so on.)

4)你建议我使用什么?我唯一想要的是当前月份、日期、小时与内存中存储的一些之间的简单比较。(例如,如果是 1 月 29 日,则显示该事件。如果是上午 19 点,则发送通知等。)

It's really a matter of personal choice. Using Calendar, for example, to compare if today is January 29, you could simply use the following:

这真的是个人选择的问题。使用Calendar,例如,比较如果今天是1月29日,你可以简单地使用以下命令:

Calendar today = Calendar.getInstance();
int dayOfMonth = today.get(Calendar.DAY_OF_MONTH);
int month = today.get(Calendar.MONTH);
if (month == Calendar.JANUARY && dayOfMonth == 29) {
  // January 29
}

回答by IgorGanapolsky

In my Android app, I am saving the date in SQLite. However, SQLite doesn't accept the Date data type. So I convert it to String like so in order to use the format YYYY-MM-DD:

在我的 Android 应用程序中,我将日期保存在 SQLite 中。但是,SQLite 不接受 Date 数据类型。因此,我将其转换为 String 以便使用格式YYYY-MM-DD

            Time today = new Time(Time.getCurrentTimezone());
            today.setToNow();
            int year = today.year;
            int month = today.month;
            int day = today.monthDay;

            Calendar gregorianCalendar = new GregorianCalendar(year, month, day);
            String entryDate =  gregorianCalendar.get(Calendar.YEAR) + "-" + gregorianCalendar.get(Calendar.MONTH) + "-" + gregorianCalendar.get(Calendar.DAY_OF_MONTH);

And it works well. I am not concerned with performance differences, as they are likely negligent.

它运作良好。我不关心性能差异,因为它们可能是疏忽大意。

回答by avest

android.text.format.Time was deprecated in API level 22. Use GregorianCalendar instead.

android.text.format.Time 在 API 级别 22 中已弃用。请改用 GregorianCalendar。

Visit http://developer.android.com/reference/android/text/format/Time.html

访问http://developer.android.com/reference/android/text/format/Time.html

As I know, there are some issues in Time class, such as Time.setJulianDay(int julianDay) will return a wrong value when the argument is smaller than julianDay of 1970.1.1

据我所知,Time 类中存在一些问题,例如 Time.setJulianDay(int julianDay) 当参数小于 1970.1.1 的 julianDay 时将返回错误值

And some bugs also happen among April, 1987-1991 (maybe is Time.set(long millis), I cannot remember).

并且在 1987-1991 年 4 月期间也发生了一些错误(可能是 Time.set(long millis),我不记得了)。

回答by Basil Bourque

tl;dr

tl;博士

ZonedDateTime.now().getDayOfMonth()

java.time

时间

As others commented, you appear to be using and mixing up java.sql.Time, java.sql.Date, java.util.Date, and java.util.Calendar.

正如其他评论,你似乎是使用和混合起来java.sql.Timejava.sql.Datejava.util.Date,和java.util.Calendar

Allof those troublesome classes are now legacy, supplanted by java.time classes added to Java 8 and later. For earlier Android, see last bullets below.

所有这些麻烦的类现在都是遗留的,被 Java 8 和更高版本中添加的 java.time 类所取代。对于早期的 Android,请参阅下面的最后一个要点。

To get the current moment in a particular time zone, use ZonedDateTime.

要获取特定时区的当前时刻,请使用ZonedDateTime

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.

时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

如果未指定时区,JVM 会隐式应用其当前默认时区。该默认值可能随时更改,因此您的结果可能会有所不同。最好将您想要/预期的时区明确指定为参数。

Specify a proper time zone namein the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as ESTor ISTas they are nottrue time zones, not standardized, and not even unique(!).

以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/regionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

ZoneId z = ZoneId.of( "America/Montreal" ) ;  

Pass the zone when asking for the current moment.

询问当前时刻时通过区域。

ZonedDateTime zdt = ZonedDateTime.now( z ) ; // Current moment as seen by the people of particular region.

Interrogate for the parts you desire.

询问您想要的部分。

Month month = zdt.getMonth() ;           // Get `Month` enum object.
int monthNumber = zdt.getMonthValue() ;  // Get month number, 1-12 for January-December.

int dayOfMonth = zdt.getDayOfMonth() ;


About java.time

关于java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多