1.Get current time in Java
This below function returns current system time
/**
* Function to return the current time
* @return The current time
* @see #getCurrentFormattedTime(String)
*/
public static Date getCurrentTime() {
Calendar calendar = Calendar.getInstance();
return calendar.getTime();
}
2. Get Current time in given format
The below Function to return the current time, formatted as per the DateFormatString setting
/**
* Function to return the current time, formatted as per the `DateFormatString setting
* @param dateFormatString The date format string to be applied
* @return The current time, formatted as per the date format string specified
* @see #getCurrentTime()
* @see #getFormattedTime(Date, String)
*/
public static String getCurrentFormattedTime(String dateFormatString) {
DateFormat dateFormat = new SimpleDateFormat(dateFormatString);
Calendar calendar = Calendar.getInstance();
return dateFormat.format(calendar.getTime());
}
3. Convert the given time into particular format and returns the same
The below function takes Time and Format as input as returns the time after changing to given format
/**
* Function to format the given time variable as specified by the DateFormatString setting
* @param time The date/time variable to be formatted
* @param dateFormatString The date format string to be applied
* @return The specified date/time, formatted as per the date format string specified
* @see #getCurrentFormattedTime(String)
*/
public static String getFormattedTime(Date time, String dateFormatString) {
DateFormat dateFormat = new SimpleDateFormat(dateFormatString);
return dateFormat.format(time);
}
4.Returns the difference between two time
/**
* Function to get the time difference between 2 {@link Date} variables in minutes/seconds format
* @param startTime The start time
* @param endTime The end time
* @return The time difference in terms of hours, minutes and seconds
*/
public static String getTimeDifference(Date startTime, Date endTime) {
long timeDifferenceSeconds = (endTime.getTime() - startTime.getTime()) / 1000; // to convert from milliseconds to seconds
long timeDifferenceMinutes = timeDifferenceSeconds / 60;
String timeDifferenceDetailed;
if (timeDifferenceMinutes >= 60) {
long timeDifferenceHours = timeDifferenceMinutes / 60;
timeDifferenceDetailed = Long.toString(timeDifferenceHours) + " hour(s), "
+ Long.toString(timeDifferenceMinutes % 60) + " minute(s), "
+ Long.toString(timeDifferenceSeconds % 60) + " second(s)";
} else {
timeDifferenceDetailed = Long.toString(timeDifferenceMinutes) + " minute(s), "
+ Long.toString(timeDifferenceSeconds % 60) + " second(s)";
}
return timeDifferenceDetailed;
}