tl;dr
ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )
.get( ChronoUnit.MINUTE_OF_HOUR )
Details
The Answer by Chenchuk is correct and should be accepted.
Some other issues covered here.
Return an integer number
You can return the minute-of-hour as an int
primitive or Integer
object rather than as a String as seen in the Question.
By the way, avoid an ambiguous name like "Time". If you mean minute-of-hour, say so.
public int getMinuteOfHour() {
int m = Integer.parseInt( yourStringGoesHere ) ;
return m ;
}
java.time
All of this is unnecessary. You are using the troublesome old legacy date-time classes now supplanted by the java.time classes. The java.time classes already provide your functionality.
Your code ignores crucial issue of time zone. If omitted, your JVM’s current default time zone is implicitly applied. Better to be specific.
We define a time zone as a ZoneId
. Use that to get a ZonedDateTime
as the current moment. Interrogate for the minute-of-hour.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( z );
int minuteOfHour = zdt.get( ChronoUnit.MINUTE_OF_HOUR );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.