Posts

Showing posts with the label DateTime

How to convert 24 hr format time in to 12 hr Format?

Here is the code to convert 24-Hour time to 12-Hour with AM and PM. If you don't want AM/PM then just replace hh:mm a with hh:mm. import java.text.SimpleDateFormat; import java.util.Date; public class Main { public static void main(String [] args) throws Exception { try { String _24HourTime = "22:15"; SimpleDateFormat _24HourSDF = new SimpleDateFormat("HH:mm"); SimpleDateFormat _12HourSDF = new SimpleDateFormat("hh:mm a"); Date _24HourDt = _24HourSDF.parse(_24HourTime); System.out.println(_24HourDt); System.out.println(_12HourSDF.format(_24HourDt)); } catch (Exception e) { e.printStackTrace(); } } } Output: Thu Jan 01 22:15:00 IST 1970 10:15 PM Another Solution: System.out.println(hr%12 + ":" + min + " " + ((hr>=12) ? "PM" : "AM"));

How to calculate time difference between a given time and current time in Java?

SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); Date date = dateFormat.parse("17:40:00"); System.out.println(date); Date date2 = new Date(); date2 = dateFormat.parse(dateFormat.format(date2)); System.out.println(date2); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); Calendar calendar2 = calendar.getInstance(); calendar2.setTime(date2); System.out.println((calendar2.getTimeInMillis() - calendar.getTimeInMillis())/60000);