Home > Software engineering >  How to make a timer based on English time
How to make a timer based on English time

Time:05-26

I use daily rewards in my game, the date in "dd/MM/yyyy" format is based on Locale.ENGLISH

final Date currentDate = Calendar.getInstance().getTime();
final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);

To make it more clear for the user, I want to count down the remaining time until the next reward, I also want to base the countdown on Locale.ENGLISH

I would like the format to be in 24h, for example if it is 12h sharp, the countdown will show 12:00:00

My current code :

long durationTime = 3600;

        new CountDownTimer(durationTime, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        @SuppressLint("DefaultLocale") String time = String.format(Locale.ENGLISH, "d:d:d", TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                                TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)-
                                TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                                TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)-
                                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));

                        final String[] hourMinSec = time.split(":");

                        timeHours.setText(hourMinSec[0]);
                        timeMinutes.setText((hourMinSec[1]));
                        timeSeconds.setText((hourMinSec[2]));
                    }
                });
            }

            @Override
            public void onFinish() {

            }
        }.start();

I need to replace the value of long durationTime

CodePudding user response:

Basically you want to calculate the difference between now and a specific date in seconds in order to display the countdown accordingly.

Based on your post, I assume the "unlocking date" of the reward is received as a string in the format dd/MM/yyyy.

You already have your corresponding SimpleDateFormat, so you can use it to parse the unlock date into a Date object:

String unlockDateAsString = "26/05/2022";
Date unlockDate = dateFormat.parse(unlockDateAsString);

The time part is initialized with 0 in that case, which is exactly what you'll need.

You can also get the current time:

Date now = new Date();

With Date.getTime() you can fetch the milliseconds since epoch. By subtracting the future milliseconds from the present milliseconds, you get the difference which then only needs to be converted to seconds.

long differenceInMilliseconds = unlockDate.getTime() - now.getTime();
long differenceInSeconds = differenceInMilliseconds / 1000;

CodePudding user response:

Never use Date and SimpleDateFormat. Those terrible legacy classes were years ago supplanted by the modern java.time classes defined in JSR 310.

Getting the current date-time requires a time zone. For any given moment, the date varies around the globe by time zone. Specify the desired/expected time zone, or ask for the JVM’s current default time zone.

ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;

Apparently you want to know the amount of time until the first moment of the next day as seen in that time zone.

Do not assume the day starts at 00:00. Some dates in some zones start at another time such as 01:00. Let java.time determine the first moment of the day.

ZonedDateTime startOfTomorrow = now.toLocalDate().plusDays( 1 ).atStartOfDay( z ) ;

Calculate time to elapse.

Duration d = Duration.between( now , startOfTomorrow ) ;

I suggest you not use clock-time format to report a duration. The ambiguity makes it easy for the user to confuse a duration for a time of day. I would build a string from the parts provided by the Duration#to…Part methods.

But if you insist, use the LocalTime class in this hack.

String output = LocalTime.MIN.plus( d ).toString() ;  // I recommend *against* using this format, but if you insist…
  • Related