Get time units hours and minutes from Date in String format
This tutorial shows how to get time units hours and minutes from Date in String format using java.text.SimpleDateFormat class. SimpleDateFormat class allows us to format date to text and to parse text to date.
Example: Time units hours and minutes from Date
package com.sneppets.example; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.ZoneId; import java.util.Date; public class HoursMinutesFromDateExample { public static void main (String[] args) { String startDateTime = "2020-02-10T10:15:00"; SimpleDateFormat sdfdatetime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); SimpleDateFormat sdfHH = new SimpleDateFormat("HH"); SimpleDateFormat sdfmm = new SimpleDateFormat("mm"); Date date; try { date = sdfdatetime.parse(startDateTime); LocalDate startDateLocal = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); System.out.println("Start Date : "+ startDateLocal); int startHour = Integer.parseInt(sdfHH.format(date)); System.out.println("Start Hour : " + startHour); int startMinute = Integer.parseInt(sdfmm.format(date)); System.out.println("Start Minute : " + startMinute); } catch (ParseException e) { e.printStackTrace(); } } }
Output
Start Date : 2020-10-02 Start Hour : 10 Start Minute : 15
Further Learning
- Java : Calculate Leap Year and Number of days in a Year
- How to Compare two Sets and check its Equality efficiently
- Find first element from a collection (List or Set)
- How to add hours to unix timestamp or epochmilli in java