0

I just want it to be displayed from current time adding 30mins till day ends Ex-Today time is 09:46AM It should display like 10:00AM,10:30AM,11:00AM....11:30PM for that particular date. But here in my code its displaying from 00:00...23:30 for whole day. Here is my code:

SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        int startDate = cal.get(Calendar.DATE);
        while (cal.get(Calendar.DATE) == startDate) {
            Log.d("time","currenttime"+cal.getTime());
            cal.add(Calendar.MINUTE, 30);
        }
Shobha Dash
  • 13
  • 1
  • 5
  • 1
    `SimpleDateFormat` and `Calendar` are poorly designed and long outdated. Instead of using them consider adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Feb 19 '19 at 18:12
  • 1
    FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android (<26) in [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Feb 19 '19 at 21:09
  • When you work on a sensitive real life project you have to think 100 times before importing an external library to do simple functionalities, leave alone a library provided by a generic Github account. For example, in some countries you cannot refer to a generic library when developing a medical app (it might not meet regulatory requirements, hence will not be approved by the health authorities) – Davi Feb 20 '19 at 19:32

2 Answers2

1

java.time and ThreeTenABP

    Duration interval = Duration.ofMinutes(30);
    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
    ZoneId zone = ZoneId.of("Europe/Podgorica");
    ZonedDateTime now = ZonedDateTime.now(zone);
    // Start at a whole half hour no earlier than now
    ZonedDateTime start = now.truncatedTo(ChronoUnit.HOURS);
    while (start.isBefore(now)) {
        start = start.plus(interval);
    }
    // End when a new day begins
    ZonedDateTime limit = now.toLocalDate().plusDays(1).atStartOfDay(zone);

    // Iterate
    ZonedDateTime currentTime = start;
    while (currentTime.isBefore(limit)) {
        System.out.println(currentTime.format(timeFormatter));
        currentTime = currentTime.plus(interval);
    }

When I ran the snippet just now, I got the following output:

20:30
21:00
21:30
22:00
22:30
23:00
23:30

Of course substitute your desired time zone where I put Europe/Podgorica.

I used the following imports:

import org.threeten.bp.Duration;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.temporal.ChronoUnit;

Question: Can I use java.time on my Android API level?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on new Android devices (from API level 26) the modern API comes built-in. In this case import from java.time with subpackages (not org.threeten.bp).
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
  • On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package org.threeten.bp and subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • V.V It require minSDKVersion 26 to run – Shobha Dash Feb 20 '19 at 02:03
  • @ShobhaDash No, it does not. On API levels under 26 it requires the ThreeTenABP library to run. Please see my edit. – Ole V.V. Feb 20 '19 at 02:53
  • Shall i add dependency com.jakewharton.threetenabp:threet – Shobha Dash Feb 20 '19 at 03:41
  • Yes, that would be the idea. – Ole V.V. Feb 20 '19 at 03:42
  • I get exception org.threeteen.bp.zone.ZoneRulesException:No time zone data files registered – Shobha Dash Feb 20 '19 at 05:46
  • Did you try pasting that message into your search engine? I think your solution is here: [ThreeTen-Backport error on Android - ZoneRulesException: No time-zone data files registered](https://stackoverflow.com/questions/38281808/threeten-backport-error-on-android-zonerulesexception-no-time-zone-data-files). – Ole V.V. Feb 20 '19 at 09:02
  • Why need to add an external library if you can easily do it yourself – Davi Feb 20 '19 at 19:23
  • @Davi Thanks for the question. An extra library is not for free, agreed, but is only until API level 26 is everywhere. Easily yourself? Did I observe correctly that it took you a couple of attempts to get your answer right? While that works now, I frankly find my code with java.time more natural to read and noticeably more maintainable. These are the pros and cons to weigh as I see it. – Ole V.V. Feb 20 '19 at 20:06
  • @Ole V.V It took me couple of attempts because OP added more questions in the comments than in the original question. And my point is simple "If I can, I have to avoid using an external library". As you said, until API 26+ are everywhere, or is provided through the SDk. – Davi Feb 20 '19 at 20:15
0

Use "HH:mm" for 24 hr format and "hh:mm a" for 12 hr format

Update 1

Below is a full example that displays what you want on a textview:

    TextView timeNow = findViewById(R.id.time_now);

    Calendar cal, atMidnight;

    //SimpleDateFormat df = new SimpleDateFormat("dd/MM/YYYY hh:mm a");
    SimpleDateFormat df = new SimpleDateFormat("hh:mm a");

    cal = Calendar.getInstance();
    atMidnight = Calendar.getInstance();

    atMidnight.add(Calendar.DATE, 1);
    atMidnight.set(Calendar.HOUR_OF_DAY, 0);
    atMidnight.set(Calendar.MINUTE, 0);
    atMidnight.set(Calendar.SECOND, 0);

    cal.add(Calendar.MINUTE, 30);

    String txt = "";

    while (cal.getTime().getTime() < atMidnight.getTime().getTime()) {
        txt = txt + df.format(cal.getTime()) + "\n";
        cal.add(Calendar.MINUTE, 30);
    }

    timeNow.setText(txt);

Update 2

To round the minutes to the next 30mins, you can do the below:

while (cal.getTime().getTime() < atMidnight.getTime().getTime()) {
    int unroundedMinutes = cal.get(Calendar.MINUTE);
    int mod = unroundedMinutes % 30;
    cal.add(Calendar.MINUTE, 30-mod);
    txt = txt + df.format(cal.getTime()) + "\n";
    cal.add(Calendar.MINUTE, 30);
    }

timeNow.setText(txt);
Davi
  • 1,031
  • 12
  • 21
  • I want it to be displayed from current time by adding 30mins.Please check the question example – Shobha Dash Feb 19 '19 at 18:09
  • In your code only current time is displayed adding 30mins but i want it to be displayed for whole day starting from current time that is why i had taken loop.ex-12:30AM,1:00.....11:30PM – Shobha Dash Feb 19 '19 at 18:40
  • FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android (<26) in [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Feb 19 '19 at 21:09
  • @Davi Can you roundup it to alike 10:30,11:00,11:30 so on – Shobha Dash Feb 20 '19 at 02:09
  • To round it to the next 30 min you need to find the mod and add it to cal minutes. check my second update – Davi Feb 20 '19 at 19:21