0

I'm trying to find the current time in my java code.

Calendar cal = Calendar.getInstance();
    Date currentLocalTime = cal.getTime();
    DateFormat date = new SimpleDateFormat("HH:mm a");
    String localTime = date.format(currentLocalTime);
    ((TextView) (mainView.findViewById(R.id.l1))).setText(localTime);

For some reason the textview displays 01:08 AM instead of 8:08 PM.

Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
  • 1
    Do you want to always get the current time in a particular time zone? – Tim Biegeleisen Jul 23 '18 at 01:15
  • 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. Much 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 in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Jul 23 '18 at 02:27
  • Zero or one? Your title says “hours value set to zero”, but the text says “ 01:08 AM”. Which seems to be the result of `SimpleDateFormat.format()`, not the hour value from the `Calendar`. Also, what is the result when you run the code at other times of day? – Ole V.V. Jul 23 '18 at 13:57
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Jul 23 '18 at 13:59
  • I cannot reproduce. Running your code at 16:00 in my time zone I get `16:00 PM`. – Ole V.V. Jul 23 '18 at 14:01
  • Tristan Wiesepape, welcome to Stack Overflow! People asking for clarification is normal here. Even if your question has been answered already, it will be helpful for other readers to [edit your question](https://stackoverflow.com/posts/51470476/edit) and provide the answers to what @TimBiegeleisen and I myself asked. Please. Also because we’d love to help. – Ole V.V. Jul 24 '18 at 10:53

3 Answers3

2

If you want the 12 hour time (8:08 PM instead of 20:08 PM) make sure to change your HH to hh like so:

DateFormat date = new SimpleDateFormat("hh:mm a");

That doesn't explain why you're seeing 01:08 AM, but it's a start. I tried the exact same code out on my system, and the time displayed properly. So, I'm not sure where your issue is. My guess is that you either have your system clock set incorrectly, or more likely your experiencing a weird issue with the Calendar and Date libraries. If you continue to experience problems I would recommend switching to the Joda-Time library. It's awesome, and it fixes all of the little issues you'll run into while using the Date and Calendar libraries.

Don Brody
  • 1,689
  • 2
  • 18
  • 30
  • 2
    FYI, the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the *java.time* classes. Much 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 in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Jul 23 '18 at 02:30
2

tl;dr

As stated in correct Answer by Don Brody, your formatting pattern was incorrect, using HH (for 24-hour clock) where it should have been lowercase hh (for 12-hour clock). You likely also have a problem with your JVM’s current default time zone not being set to what you expect.

Also… Your problem is moot. You are using terrible old classes that were supplanted years ago by java.time.

LocalTime                                  // Represent time-of-day without date and without time zone.
.now()                                     // Capture the current time-of-day as seen in the JVM’s current default time zone. Better to pass the optional `ZoneId` argument to specify explicitly the desired/expected time zone.
.format(                                   // Generate a `String` representing our time-of-day value.
    DateTimeFormatter
    .ofLocalizedTime( FormatStyle.SHORT )  // Automatically localize rather than hard-code a specific formatting pattern.
    .withLocale( Locale.US )               // Locale determines the human language and cultural norms used in localizing.
)                                          // Returns a `String` object.

10:09 PM

Use java.time

You are using terrible old classes now supplanted by the java.time classes.

Get the current time-of-day.

LocalTime lt = LocalTime.now() ;  // Capture the current time-of-day using the JVM’s current default time zone.

Better to explicitly state the desired/expected time zone than rely implicitly on the JVM’s current default time zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalTime lt = LocalTime.now( z ) ;

Generate a string in AM-PM format.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "hh:mm a" ) ;  // Lowercase `hh` for 12-hour clock, uppercase `HH` for 24-hour clock.
String output = lt.format( f ) ;

Even better, let java.time automatically localize for you.

Locale locale = Locale.US ;
DateTimeFormatter f2 = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( locale ) ;
String output2 = lt.format( f2 ) ;

See that code run live at IdeOne.com.

lt.toString(): 22:09:19.825

output: 10:09 PM

output2: 10:09 PM


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

You can use the following code:

Date currentDate = Calendar.getInstance(TimeZone.getDefault()).getTime()

Check out this other question that might be an answer to your problem. How to get the current date and time of your timezone in Java?

Alifyz Pires
  • 73
  • 1
  • 7
  • I don’t think it makes any difference. You will get the current time just as in the question (and just as in the question the `Date` object cannot hold a time zone in it). – Ole V.V. Jul 23 '18 at 13:51