简体   繁体   中英

Updating date from SimpleDateFormat Android?

I've used SimpleDateFormat in my Android app. Like this:

final TextView date = (TextView) findViewById(R.id.date);

long datesdf = System.currentTimeMillis();

SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM, yyyy");
String dateString = sdf.format(datesdf);
date.setText(dateString);
date.setTextSize(17);

By which I get output example: 01 May, 2015

But the problem is the date, month or year doesn't get updated, what's wrong with it? Thanks in advance!

You have to manually update the date when required. Per your code, datesdf holds the current time from when the code is run. This (and the date string you build from it etc.) doesn't change/update by itself.

If you just want to detect when a new day starts you could use AlarmManager and schedule an alarm for midnight. However, this should only be required when your app is in use. For example, you can update the date once when the app/Activity is started and schedule an alarm then. When the Activity is paused you don't need the alarm anymore and can cancel it.

SimpleDateFormat date = new SimpleDateFormat("dd-MMM-yyyy");
    String formattedDate = date.format(c.getTime());
    SimpleDateFormat time = new SimpleDateFormat("hh:mm:ss a");
    String formattedTime = time.format(c.getTime());

use this code for updating date and time also

Guys I found my solution on my own and it's working like charm. Here's the solution:

final TextView date = (TextView) findViewById(R.id.date);

final Handler date_handler = new Handler(getMainLooper());
        date_handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                date.setText(new SimpleDateFormat("dd MMMM, yyyy", Locale.US)
                        .format(new Date()));
                date_handler.postDelayed(this, 1000);
            }
        }, 10);

It updates the date, month and year automatically and it works 100%!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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