Java get hours and minutes

Get hours and minutes between local time in different time zone

The following code shows how to get hours and minutes between local time in different time zone.

Example

 import java.time.LocalTime; import java.time.ZoneId; import java.time.temporal.ChronoUnit; /*from w ww. j a v a 2 s . com*/ public class Main < public static void main(String. args) < ZoneId zone1 = ZoneId.of("Europe/Berlin"); ZoneId zone2 = ZoneId.of("Brazil/East"); LocalTime now1 = LocalTime.now(zone1); LocalTime now2 = LocalTime.now(zone2); System.out.println(now1); System.out.println(now2); long hoursBetween = ChronoUnit.HOURS.between(now1, now2); long minutesBetween = ChronoUnit.MINUTES.between(now1, now2); System.out.println(hoursBetween); System.out.println(minutesBetween); > > 

The code above generates the following result.

Источник

Java: getMinutes and getHours

Try using Joda Time instead of standard java.util.Date classes. Joda Time library has much better API for handling dates.

DateTime dt = new DateTime(); // current time int month = dt.getMonth(); // gets the current month int hours = dt.getHourOfDay(); // gets hour of day 

See this question for pros and cons of using Joda Time library.

Joda Time may also be included to some future version of Java as a standard component, see JSR-310.

If you must use traditional java.util.Date and java.util.Calendar classes, see their JavaDoc’s for help (java.util.Calendar and java.util.Date).

Читайте также:  What html color is that

You can use the traditional classes like this to fetch fields from given Date instance.

Date date = new Date(); // given date Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance calendar.setTime(date); // assigns calendar to given date calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format calendar.get(Calendar.HOUR); // gets hour in 12h format calendar.get(Calendar.MONTH); // gets month number, NOTE this is zero based! 

Solution 2

From the Javadoc for Date.getHours

As of JDK version 1.1, replaced by Calendar.get(Calendar.HOUR_OF_DAY)

Calendar rightNow = Calendar.getInstance(); int hour = rightNow.get(Calendar.HOUR_OF_DAY); 

and the equivalent for getMinutes.

Solution 3

java.time

While I am a fan of Joda-Time, Java 8 introduces the java.time package which is finally a worthwhile Java standard solution! Read this article, Java SE 8 Date and Time, for a good amount of information on java.time outside of hours and minutes.

In particular, look at the LocalDateTime class.

LocalDateTime.now().getHour(); LocalDateTime.now().getMinute(); 

Solution 4

First, import java.util.Calendar

Calendar now = Calendar.getInstance(); System.out.println(now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE)); 

Solution 5

tl;dr

ZonedDateTime

The Answer by J.D. is good but not optimal. That Answer uses the LocalDateTime class. Lacking any concept of time zone or offset-from-UTC, that class cannot represent a moment.

ZoneId z = ZoneID.of( "America/Montreal" ) ; ZonedDateTime zdt = ZonedDateTime.now( z ) ; 

Specify time zone

If you omit the ZoneId argument, one is applied implicitly at runtime using the JVM’s current default time zone.

ZonedDateTime.now( ZoneId.systemDefault() ) 

Better to be explicit, passing your desired/expected time zone. The default can change at any moment during runtime.

If critical, confirm the time zone with the user.

Hour-minute

Interrogate the ZonedDateTime for the hour and minute.

int hour = zdt.getHour() ; int minute = zdt.getMinute() ; 

LocalTime

If you want just the time-of-day without the time zone, extract LocalTime .

LocalTime lt = zdt.toLocalTime() ; 

Or skip ZonedDateTime entirely, going directly to LocalTime .

LocalTime lt = LocalTime.now( z ) ; // Capture the current time-of-day as seen in the wall-clock time used by the people of a particular region (a time zone). 

java.time types

Table of types of date-time classes in modern java.time versus legacy.

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 .

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

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

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?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later — Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    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.

    Java Programming Tutorial - 36 - Time Class

    Getters and Setters - Learn Getters and Setters in Java

    Date.prototype.getHours()-JavaScript Functions-ES6/ECMA2015/JavaScript 2019/JS

    GetHours , getMinutes , getSeconds , getMilliSeconds methods of Date object

    getHours() getMinutes() getSeconds() Metodu Kullanımı Javascript

    Chapter 3: VN 3.3 Solving the 12-hour clock exercise

    Java 32. Hiểu rõ phương thức GET và SET | Phần 2 - Lập trình Hướng Đối Tượng

    How To Convert Seconds To Hours Minutes Seconds In JAVA

    Java 80. Cách sử dụng JPanel và cấu hình Look and Feel cho giao diện chương trình Java

    rink.attendant.6

    Software engineer in Ottawa. I’m most familiar with web technologies, particularly HTML, CSS, JavaScript/TypeScript, PHP, and SQL. As a member of the Stack Exchange network, I strive to learn something new every day. #SOreadytohelp I currently work as a security analyst at the University of Ottawa on the IT Services and Infrastructure team, specializing in web application security. In the IT field, I’ve also worked for: University of Ottawa, as a Programmer Analyst on the Student Life Solutions team under IT Solutions Esri Inc., as a Software Engineer Intern on the Esri Maps for Cognos team Canadian Cyber Incident Response Centre (Public Safety Canada), as a Web Application Developer (CO-OP job) Statistics Canada, as a Systems Tester (CO-OP job) Kenora District Services Board, as a Web Application Developer (officially EMS Resource Assistant)

    Updated on August 20, 2021

    Comments

    How do you get Hours and Minutes since Date.getHours and Date.getMinutes got deprecated? The examples that I found on Google search used the deprecated methods.

    Basil Bourque

    FYI, the terribly troublesome date-time classes such as java.util.Date , java.util.Calendar , and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

    Источник

    Java java get current hour and minute

    Finally I ended up creating my own class: Use: Solution 3: There’s something really powerful out there called Joda Time it provides a quality replacement for the Java date and time classes. Solution 1: Joda-Time Use Joda Time, in particular LocalTime. java.time Similarly, the java.time package built into Java 8 also offers a class.

    TimePicker.getHour() and TimePicker.getMinute() returns current hour and minute

     alarmEkleBtn.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < hour = timePicker.getHour(); minute = timePicker.getMinute(); listener.alarmBilgisiGetir(hour, minute, quantity); dismiss(); >>); 

    This portion of your code is inside of onCreateDialog method:

    if (Build.VERSION.SDK_INT >= 23 ) < // getHour and getMinute returns current hour and minute hour = timePicker.getHour(); minute = timePicker.getMinute(); Log.i("mert", "getHour:getMinute - " + hour + ":" + minute); >else

    Which means that you are assigning a value to hour and minute AT THE MOMENT of the dialog’s creation, at which point it just returns the current time. What you want to do is move that whole block of code inside of the submit button ‘s on click listener:

    alarmEkleBtn.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < // --------------->>>>>PUT THAT CODE HERE INSTEAD! >); 

    This way you’ll actually get the latest set value from the picker.

    Java — Get current time of day in seconds, Or more simply you could convert the LocalDateTime to a LocalTime instance and then apply the toSecondOfDay () method : LocalDateTime date = LocalDateTime.now (); int seconds = date.toLocalTime ().toSecondOfDay (); From the java.time.LocalTime javadoc : public int toSecondOfDay () Extracts the time …

    Get Hour and Minute from timestamp in Java

    Although not clear from how you phrase your question, the only reasonable explanation is that the exception is not thrown, but you refer to a compiler error.

    ParseException is a checked exception and must be handled by your source code, otherwise it will not compile. I am not sure which compiler you are using, the Java compiler from Oracle’s JDK gives a more detailed error description:

    error: unreported exception ParseException; must be caught or declared to be thrown

    If you just want to get the part of the string that has «18:08» and you don’t want to adjust according to timezone, then you could just use String#substring(start, end) in order to extract that part of the string.

    String fullTime = "2016-03-23 18:08:59"; String timeStr = fullTime.substring(11, 16); //extract "HH:mm" from "yyyy-MM-dd HH:mm:ss" 

    If you DO want to adjust according to timezone, then add a try block.

    String fullTime = "2016-03-23 18:08:59"; DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), df2 = new SimpleDateFormat("HH:mm"); df1.setTimeZone(TimeZone.getTimeZone("UTC")); df2.setTimeZone(TimeZone.getTimeZone("IST")); String timeStr = ""; try < timeStr = df2.format(df1.parse(fullTime)); //parse throws ParseException >catch (ParseException e) < /* handle this */ >

    This code takes the variable at the top as input in order to change timeStr to the value at «HH:mm» after adjusting the timezone.

    String — Current system time +1 minute in java, 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, …

    Best way to handle only hours and minutes in Java

    Joda-Time

    Use Joda Time, in particular LocalTime.

    LocalTime time = new LocalTime(12, 20); 

    java.time

    Similarly, the java.time package built into Java 8 also offers a LocalTime class.

    very good response naumcho but unfortunately I can not use that version of java. Finally I ended up creating my own class:

    public class Tiempo < public Integer hora; public Integer minuto; public Integer segundo; public Tiempo()<>public Tiempo(String tiempo) < this.parse(tiempo); >/** * Convierte un tiempo de tipo String a formato Tiempo * @param tiempo Tiempo en formato HH:mm:ss (24 horas) * @return Retorna true si fué convertido correctamente, en caso contrario retorna false. */ public Boolean parse(String tiempo)< try< this.hora = Integer.parseInt(tiempo.split(":")[0]); this.minuto = Integer.parseInt(tiempo.split(":")[1]); this.segundo = Integer.parseInt(tiempo.split(":")[2]); Boolean valido = ( (this.hora >= 0) && (this.hora = 0) && (this.minuto = 0) && (this.segundo else < this.hora = null; this.minuto = null; this.segundo = null; return false; >>catch(Exception e) < this.hora = null; this.minuto = null; this.segundo = null; return false; >> /** * * @param a Tiempo a comparar * @param b Tiempo a comparar * @return Retorna un número negativo si a es menor que b, retorna 0 si son iguales, retorna un número positivo si a es mayor que b, retorna null si uno de ambos tiempos era nulo */ static public Integer comparar(Tiempo a, Tiempo b) < if((a == null) || (b == null))< return null; >if(a.hora < b.hora) < return -1; >else if(a.hora == b.hora)< if(a.minuto < b.minuto)< return -2; >else if(a.minuto == b.minuto)< if(a.segundo < b.segundo)< return -3; >else if(a.segundo == b.segundo)< return 0; >else if(a.segundo > b.segundo) < return 3; >>else if(a.minuto > b.minuto) < return 2; >>else if(a.hora > b.hora) < return 1; >return null; > > 
    Tiempo a = new Tiempo("09:10:05"); Tiempo b = new Tiempo("15:08:31"); if(Tiempo.compare(a, b) < 0)< // a

    There's something really powerful out there called Joda Time it provides a quality replacement for the java date and time classes.

    Java getHours(), getMinutes() and getSeconds(), As I know getHours (), getMinutes () and getSeconds () are all deprecated in Java and they are replaced with Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND. These will in fact return the hour, minute and second for that particular moment. However, I would want to retrieved the hours …

    Get the specific 15 minutes timeframe based on current time

    You could create a TemporalAdjuster that calculates the end of the current 15-minute period and calculate the start of the period by removing 14 minutes.

    public static void main(String[] args) < LocalTime t = LocalTime.of(12, 34); LocalTime next15 = t.with(next15Minute()); System.out.println(next15.minusMinutes(14) + " - " + next15); >public static TemporalAdjuster next15Minute() < return (temporal) ->< int minute = temporal.get(ChronoField.MINUTE_OF_DAY); int next15 = (minute / 15 + 1) * 15; return temporal.with(ChronoField.NANO_OF_DAY, 0).plus(next15, ChronoUnit.MINUTES); >; > 

    Note: I'm not sure how it behaves around DST changes - to be tested.

    You can simply use the Date API and calculate the intervals. Divide with your interval (15 min) and multiply again. This will strip off the minutes and round to the lower 15 minutes interval. Now you have to add fifteen minutes to get your needed output. See the following code:

    import java.util.*; import java.lang.*; import java.io.*; class Ideone < public static void main (String[] args) throws java.lang.Exception < long ms = new Date().getTime(); System.out.println("Current time: " + new Date().toString()); long fifteen = 15 * 60 * 1000; long newMs = (ms / fifteen) * fifteen + fifteen; System.out.println("Calculated time: " + new Date(newMs)); >> 

    Running example with LocalDate

    import java.util.*; import java.lang.*; import java.io.*; import java.time.*; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; class Ideone < public static void main (String[] args) throws java.lang.Exception < LocalTime now = LocalTime.now(); System.out.println(now); LocalTime next = now.with((temp) ->< int currentMinute = temp.get(ChronoField.MINUTE_OF_DAY); int interval = (currentMinute / 15) * 15 + 15; temp = temp.with(ChronoField.SECOND_OF_MINUTE, 0); temp = temp.with(ChronoField.MILLI_OF_SECOND, 0); return temp.with(ChronoField.MINUTE_OF_DAY, interval); >); System.out.println(next); > > 

    Here is a simpler approach with LocalTime

    public static void main(String[] args) < int interval = 15; //Can be customized to any value LocalTime now = LocalTime.now(); int minuteOfDay = now.toSecondOfDay() / 60; int mod = (minuteOfDay / interval + 1) * interval; System.out.println("lower bound" + LocalTime.ofSecondOfDay((mod - interval) * 60)); System.out.println("Upper bound" + LocalTime.ofSecondOfDay(mod * 60)); >

    Get the current hour and minutes from Instant.now(), If you want to know the single parts of an Instant for the time zone of your system, then do this: public static void main (String [] args) < Instant instant = Instant.now (); // convert the instant to a local date time of your system time zone LocalDateTime ldt = LocalDateTime.ofInstant (instant, ZoneId.systemDefault ()); …

    Источник

Оцените статью