java - 时间与日期与日历java

标签 java android date time calendar

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

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

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

或者这个

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

我的问题是:

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

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

3)我尝试了我找到的这段代码:

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

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

怎么了?

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

最佳答案

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

它们既稳定又经过良好测试,尤其是 Calendar,它自 JDK1.1 起就包含在 Java API 中。同样来自 docs 时间:

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.

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

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

是的,他们有。您可以使用 Calendar.getInstance(java.util.TimeZone) 指定 TimeZone .否则,将使用默认值。

3) I tried this code that I have found:

代码工作得很好。例如,确保您使用的是 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.)

这真的是个人选择的问题。例如,使用 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
}

关于java - 时间与日期与日历java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12334972/

相关文章:

java - 计算行驶的距离(不是之间的距离)

objective-c - Objective-C 中的星期几

javascript 检查日期对象是否至少存在 5 分钟(nodeJS)

Java正则表达式至少匹配斯堪的纳维亚字母之一

Java 警告 : [options] system modules path not set in conjunction with -source 11

java - 我们如何使用mockito来获取对象

java - 底部导航栏未在 Activity 中显示

android - 关于 S3 和 S2 中 Android 图像大小的问题?

java - 如何获取上个月的第一个日期和最后一个日期? ( java )

java - 无法解析 no.nordicsemi.android.support.v18 :scanner