获取当前日期和时间

Getting Current date and time

我尝试按如下方式访问 android 应用程序中的当前日期时间:

 Calendar c = Calendar.getInstance();
 int seconds = c.get(Calendar.SECOND);
            //long time = System.currentTimeMillis();
 Date date2 = new Date(seconds);
 Log.d(">>>>>>>Current Date : ",""+date2);

它给我 1970 年的日期和时间如下:

>>>>>>>Current Date :﹕ Thu Jan 01 05:30:00 GMT+05:30 1970

但是,应该是 2015 年而不是 1970 年。 问题是什么?

I have solved above problem from solution provided. Atually, I am generating notification as the datetime value from the databse matches to the current datetime value. but, it does not generating notification.

我的代码如下:

public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    doAsynchTask = new TimerTask() {

        @Override
        public void run() {
            Log.d("Timer Task Background", "Timer task background");
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            long time = System.currentTimeMillis();
            Date dateCurrent = new Date(time);
            Log.d(">>>>>>>Current Date : ", "" + dateCurrent);

            getListData();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
            Date dateFromDatabase;
            for (int i = 0; i < remiderList.size(); i++) {

                try {
                    System.out.print("+++" + remiderList.get(i).toString());
                    dateFromDatabase = formatter.parse(remiderList.get(i).toString());
                    Log.d(">>>>>Database date  : ", "" + dateFromDatabase);
                    if (dateCurrent.equals(dateFromDatabase)) {
                        Toast.makeText(getApplicationContext(), "Date matched", Toast.LENGTH_LONG).show();

                        displayNotification();
                    }


                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }

    };
    timer.schedule(doAsynchTask, 0, 1000);


}

public void displayNotification() {
    Notification.Builder builder = new Notification.Builder(MyRemiderService.this);


    Intent intent1 = new Intent(this.getApplicationContext(),
            HomeActivity.class);
    Notification notification = new Notification(R.drawable.notification_template_icon_bg,
            "This is a test message!", System.currentTimeMillis());
    intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
            | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
            this.getApplicationContext(), 0, intent1,
            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setSmallIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha)
            .setContentTitle("ContentTitle").setContentText("this for test massage")
            .setContentIntent(pendingNotificationIntent);

    notification = builder.getNotification();
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
   /* notification.setLatestEventInfo(this.getApplicationContext(),
            "AlarmManagerDemo", "This is a test message!",
            pendingNotificationIntent);*/

    mManager.notify(0, notification);
}

@Override
public void onDestroy() {

    super.onDestroy();
}

public void getListData() {
    remiderList = dbHelper.getAllRemiders();
}

我已经检查了 Logcat 中的两个值,如下所示:

09-15 17:50:00.629  17915-17927/? D/>>>>>>>Current Date :﹕ Tue Sep 15 17:50:00 GMT+05:30 2015

09-15 17:50:00.637  17915-17927/? D/>>>>>Database date  :﹕ Tue Sep 15 17:50:00 GMT+05:30 2015

试试这个

private String getCurrentDateAndTime() {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
        return simple.format(new Date());
    }

您尚未在日历对象中设置当前日期。

 Calendar c = Calendar.getInstance();
    c.setTime(new Date());
    //Calendar.SECOND will return only seconds from the date
    //int seconds = c.get(Calendar.SECOND);
    long time = c.getTime();
    Date date2 = new Date(time);
    Log.d(">>>>>>>Current Date : ",""+date2);

您可以使用 SimpleDateFormat class 将日期格式化如下

SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
System.out.println(format.format(new Date()));

避免使用旧的日期时间 classes

您正在使用与 Java 的最早版本捆绑在一起的旧日期时间 classes,例如 java.util.Date/.Calendar。它们已被证明设计不当、令人困惑和麻烦。避开它们。

在许多混淆点中,java.util.Date 代表日历日期 一天中的时间,而 java.sql.Date 假装代表只有一个没有任何时间的日期,尽管它实际上有一个时间设置为零 (00:00:00.0)。

java.time

旧的日期时间 classes 已被 java.time framework. See Tutorial 取代。

java.sql

最终我们应该看到 JDBC 驱动程序更新为直接处理 java.time 类型。到那时,我们仍然需要 java.sql 类型来获取数据库的数据 in/out。但是立即调用添加到旧 classes 的新转换方法以移动到 java.time 类型。

Instant

一个Instant is a moment on the timeline in UTC with resolution up to nanoseconds.

java.sql.Timestamp ts = myResultSet.getTimestamp( x );
Instant instant = ts.toInstant();

LocalDate

如果您要比较该日期时间的日期部分与今天的日期,请使用 LocalDate class。 class 真正代表了一个没有时间和时区的纯日期值。

时区

请注意,时区对于确定日期来说至关重要,因为在任何给定时刻,世界各地的日期可能因时区而异。因此,在提取 LocalDate 之前,我们需要应用时区 (ZoneId) to get a ZonedDateTime。如果您省略时区,则会隐式应用 JVM 当前的默认时区。最好明确指定 desired/expected 时间区域。

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
LocalDate today = LocalDate.now( zoneId );
if( today.isEqual( zdt.toLocalDate() ) {
    …
}

请注意,我们在该代码中的任何地方都没有使用字符串;所有日期时间对象。

格式化字符串

要生成 String 作为日期时间值的文本表示,您可以调用 toString 方法以使用 ISO 8601 标准格式化文本。或者指定您自己的格式化模式。更好的是,让 java.time 自动完成本地化工作。为人类语言(英语、法语等)指定 Locale 以用于翻译 day/month 等名称。

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) );  // Or Locale.CANADA_FRENCH and so on.