简体   繁体   English

获取当前日期和时间

[英]Getting Current date and time

I tried to access current datetime in android application as follows : 我试图在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);

It gives me date and time with the year 1970 as follows : 它给了我1970年的日期和时间,如下所示:

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

but, It should be 2015 instead of 1970. What the problem is ? 但是,应该是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. 通常,我正在生成通知,因为数据库中的datetime值与当前datetime值匹配。 but, it does not generating notification. 但是,它不会生成通知。

My code is as follows : 我的代码如下:

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();
}

I have checked both the values in Logcat as follows : 我已经检查了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

You have not set current date in calender object. 您尚未在日历对象中设置当前日期。

 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);

You can use SimpleDateFormat class to format the dates as follow 您可以使用SimpleDateFormat类来格式化日期,如下所示

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

try this 尝试这个

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

Avoid old date-time classes 避免使用旧的日期时间类

You are using the old date-time classes bundled with the earliest versions of Java such as java.util.Date/.Calendar. 您正在使用与Java最早版本捆绑在一起的旧日期时间类,例如java.util.Date/.Calendar。 They have proven to be poorly designed, confusing, and troublesome. 它们被证明设计不当,令人困惑且麻烦。 Avoid them. 避免他们。

Among the many points of confusion is that a java.util.Date represents a calendar date and a time-of-day while a java.sql.Date pretends to represent only a date without any time-of-day although it does actually have a time-of-day just set to zeros ( 00:00:00.0 ). 在许多混淆点中,一个java.util.Date代表一个日历日期一个时间,而一个java.sql.Date假装仅代表一个没有任何时间的日期,尽管实际上它确实具有将一天中的时间设置为零( 00:00:00.0 )。

java.time java.time

The old date-time classes have been supplanted by the java.time framework. java.time框架已取代了旧的日期时间类。 See Tutorial . 请参阅教程

java.sql java.sql

Eventually we should see JDBC drivers updated to deal with java.time types directly. 最终,我们应该看到JDBC驱动程序已更新,可以直接处理java.time类型。 Until then, we still need the java.sql types for getting data in/out of databases. 在此之前,我们仍然需要java.sql类型来将数据移入 /移出数据库。 But immediately call the new conversion methods added to the old classes to move into java.time types. 但是,请立即调用添加到旧类中的新转换方法,以移入java.time类型。

Instant

An Instant is a moment on the timeline in UTC with resolution up to nanoseconds . Instant是UTC时间线上的时刻,分辨率高达纳秒

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

LocalDate

If you are trying to compare the date-portion of that date time to today's date, use the LocalDate class. 如果要比较该日期时间的日期部分和今天的日期,请使用LocalDate类。 This class truly represents a date-only value without time-of-day and without time zone. 此类真正表示没有日期和时区的仅日期值。

Time Zone 时区

Note that a time zone is crucial to determining dates, as the date may vary around the world by time zone for any given moment. 请注意,时区对于确定日期至关重要 ,因为在任何给定时刻,该日期可能会在世界各地随时区而变化。 So before extracting the LocalDate we need to apply a time zone ( ZoneId ) to get a ZonedDateTime . 因此,在提取LocalDate之前,我们需要应用一个时区( ZoneId )以获取ZonedDateTime If you omit the time zone your JVM's current default time zone is implicitly applied. 如果省略时区,则将隐式应用JVM的当前默认时区。 Better to specify explicitly the desired/expected time zone. 最好明确指定所需/预期的时区。

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() ) {
    …
}

Notice that nowhere in that code did we use Strings; 注意,在该代码中没有任何地方使用字符串。 all date-time objects instead. 所有日期时间对象。

Formatting Strings 格式化字符串

To generate a String as a textual representation of the date-time value, you can call the toString methods to get text formatted using the ISO 8601 standard. 要生成String作为日期时间值的文本表示形式,可以调用toString方法以使用ISO 8601标准获取格式化的文本。 Or specify your own formatting pattern. 或指定您自己的格式设置模式。 Better yet, let java.time do the work of localizing automatically. 更好的是,让java.time自动执行本地化工作。 Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and such. 指定人类语言(英语,法语等)的语言Locale ,以翻译日/月等名称。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM