Getting Current date and time

2019-09-20 03:05发布

问题:

I tried to access current datetime in android application as follows :

 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 :

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

but, It should be 2015 instead of 1970. What the problem is ?

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.

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 :

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

回答1:

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 format = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
System.out.println(format.format(new Date()));


回答2:

try this

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


回答3:

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. 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.time

The old date-time classes have been supplanted by the java.time framework. See Tutorial.

  • Java 8 and later: The java.time framework is built-in.
  • Java 7 & 6: Use the backport of java.time.
  • Android: Use this wrapped version of that backport.

java.sql

Eventually we should see JDBC drivers updated to deal with java.time types directly. Until then, we still need the java.sql types for getting data in/out of databases. But immediately call the new conversion methods added to the old classes to move into java.time types.

Instant

An 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

If you are trying to compare the date-portion of that date time to today’s date, use the LocalDate class. 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. If you omit the time zone your JVM’s current default time zone is implicitly applied. 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. Or specify your own formatting pattern. Better yet, let java.time do the work of localizing automatically. Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and such.

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