Java format hour and min - java

I need to format my time string such as this:
int time = 160;
Here's my sample code:
public static String formatDuration(String minute) {
String formattedMinute = null;
SimpleDateFormat sdf = new SimpleDateFormat("mm");
try {
Date dt = sdf.parse(minute);
sdf = new SimpleDateFormat("HH mm");
formattedMinute = sdf.format(dt);
} catch (ParseException e) {
e.printStackTrace();
}
return formattedMinute;
// int minutes = 120;
// int h = minutes / 60 + Integer.parseInt(minute);
// int m = minutes % 60 + Integer.parseInt(minute);
// return h + "hr " + m + "mins";
}
I need to display it as 2hrs 40mins. But I don't have a clue how to append the "hrs" and "mins". The requirement is not to use any library.
If you've done something like this in the past, feel free to help out. Thanks a bunch!

Since, it's 2018, you really should be making use of the Date/Time libraries introduced in Java 8
String minutes = "160";
Duration duration = Duration.ofMinutes(Long.parseLong(minutes));
long hours = duration.toHours();
long mins = duration.minusHours(hours).toMinutes();
// Or if you're lucky enough to be using Java 9+
//String formatted = String.format("%dhrs %02dmins", duration.toHours(), duration.toMinutesPart());
String formatted = String.format("%dhrs %02dmins", hours, mins);
System.out.println(formatted);
Which outputs...
2hrs 40mins
Why use something like this? Apart of generally been a better API, what happens when minutes equals something like 1600?
Instead of printing 2hrs 40mins, the above will display 26hrs 40mins. SimpleDateFormat formats date/time values, it doesn't deal with duration

int minutes = 160;
int h = minutes / 60;
int m = minutes % 60;
String.format("%d hr %d mins",h,m); // output : 2 hr 40 mins

Just try
sdf = new SimpleDateFormat("HH 'hrs' mm 'mins'");
There is a good documentation https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
From the doc:
"Text can be quoted using single quotes (') to avoid interpretation."

Another simple approach could be something along the lines:
public static String formatDuration(String minute){
int minutes = Integer.parseInt(minute);
int hours = minutes / 60;
minutes = minutes % 60;
return hours + "hrs " + minutes + "mins.";
}

Related

Converting time String to Long generates wrong value

I have a time String "00:01:00". When I convert it to long by SimpleDateFormat("HH:mm:ss), I'm getting 10860000 milliseconds, equivalent to 03:01:00.
For "00:59:00" I'm getting "03:57:00", so I don't know what's happening but it's adding 3hours to my milliseconds.
Code:
String time = String.format("%02d",hourOfDay) + ":" + String.format("%02d", minute) + ":" + String.format("%02d", seconds);
tvTimer.setText(time);
try {
DateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
Time timeValue = new Time(formatter.parse(time).getTime());
long initTimer = timeValue.getTime
} catch (ParseException e) {
e.printStackTrace();
}
CountDownTimer:
timer = new CountDownTimer(initTimer, 1000) {
#Override
public void onTick(long l) {
long secondsInMilli = initTimer / 1000;
long minutesInMilli = secondsInMilli / 60;
long hoursInMilli = minutesInMilli / 60;
long elapsedSeconds = secondsInMilli % 60;
long elapsedMinutes = minutesInMilli % 60;
long elapsedHours = hoursInMilli % 60;
tvTimer.setText(String.format("%02d", elapsedHours) + ":" + String.format("%02d", elapsedMinutes) +":" + String.format("%02d", elapsedSeconds));
}
I think you have a time zone problem. The string "00:01:00" does not specify a world time, because there is no time zone on it. The parsing will be done on some default time zone, and your offset is evidently 3 (mine seems to be -5).
If you parse "00:01:00 GMT" with ("HH:mm:ss z"), you get the 60000 milliseconds you expect.
Try setting the Timezone after instantiating the formatter, as next:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
or if you need the local time zone then:
formatter.setTimeZone(Calendar.getInstance().getTimeZone());

How to get Time ago in android? [duplicate]

I have two date like:
String date_1="yyyyMMddHHmmss";
String date_2="yyyyMMddHHmmss";
I want to print the difference like:
2d 3h 45m
How can I do that? Thanks!
DateTimeUtils obj = new DateTimeUtils();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/M/yyyy hh:mm:ss");
try {
Date date1 = simpleDateFormat.parse("10/10/2013 11:30:10");
Date date2 = simpleDateFormat.parse("13/10/2013 20:35:55");
obj.printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
//1 minute = 60 seconds
//1 hour = 60 x 60 = 3600
//1 day = 3600 x 24 = 86400
public void printDifference(Date startDate, Date endDate) {
//milliseconds
long different = endDate.getTime() - startDate.getTime();
System.out.println("startDate : " + startDate);
System.out.println("endDate : "+ endDate);
System.out.println("different : " + different);
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
System.out.printf(
"%d days, %d hours, %d minutes, %d seconds%n",
elapsedDays, elapsedHours, elapsedMinutes, elapsedSeconds);
}
out put is :
startDate : Thu Oct 10 11:30:10 SGT 2013
endDate : Sun Oct 13 20:35:55 SGT 2013
different : 291945000
3 days, 9 hours, 5 minutes, 45 seconds
Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
Date today = new Date();
long diff = today.getTime() - userDob.getTime();
int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
int hours = (int) (diff / (1000 * 60 * 60));
int minutes = (int) (diff / (1000 * 60));
int seconds = (int) (diff / (1000));
Short & Sweet:
/**
* Get a diff between two dates
*
* #param oldDate the old date
* #param newDate the new date
* #return the diff value, in the days
*/
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
try {
return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
Usage:
int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);
Output:
dateDifference: 2
Kotlin Version:
#ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
return try {
DurationUnit.DAYS.convert(
format.parse(newDate).time - format.parse(oldDate).time,
DurationUnit.MILLISECONDS
)
} catch (e: Exception) {
e.printStackTrace()
0
}
}
This works and convert to String as a Bonus ;)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//Dates to compare
String CurrentDate= "09/24/2015";
String FinalDate= "09/26/2015";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");
//Setting dates
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
//Comparing dates
long difference = Math.abs(date1.getTime() - date2.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
Log.e("HERE","HERE: " + dayDifference);
} catch (Exception exception) {
Log.e("DIDN'T WORK", "exception " + exception);
}
}
It will give you difference in months
long milliSeconds1 = calendar1.getTimeInMillis();
long milliSeconds2 = calendar2.getTimeInMillis();
long periodSeconds = (milliSeconds2 - milliSeconds1) / 1000;
long elapsedDays = periodSeconds / 60 / 60 / 24;
System.out.println(String.format("%d months", elapsedDays/30));
Here is the modern answer. It’s good for anyone who either uses Java 8 or later (which doesn’t go for most Android phones yet) or is happy with an external library.
String date1 = "20170717141000";
String date2 = "20170719175500";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
Duration diff = Duration.between(LocalDateTime.parse(date1, formatter),
LocalDateTime.parse(date2, formatter));
if (diff.isZero()) {
System.out.println("0m");
} else {
long days = diff.toDays();
if (days != 0) {
System.out.print("" + days + "d ");
diff = diff.minusDays(days);
}
long hours = diff.toHours();
if (hours != 0) {
System.out.print("" + hours + "h ");
diff = diff.minusHours(hours);
}
long minutes = diff.toMinutes();
if (minutes != 0) {
System.out.print("" + minutes + "m ");
diff = diff.minusMinutes(minutes);
}
long seconds = diff.getSeconds();
if (seconds != 0) {
System.out.print("" + seconds + "s ");
}
System.out.println();
}
This prints
2d 3h 45m
In my own opinion the advantage is not so much that it is shorter (it’s not much), but leaving the calculations to an standard library is less errorprone and gives you clearer code. These are great advantages. The reader is not burdened with recognizing constants like 24, 60 and 1000 and verifying that they are used correctly.
I am using the modern Java date & time API (described in JSR-310 and also known under this name). To use this on Android under API level 26, get the ThreeTenABP, see this question: How to use ThreeTenABP in Android Project. To use it with other Java 6 or 7, get ThreeTen Backport. With Java 8 and later it is built-in.
With Java 9 it will be still a bit easier since the Duration class is extended with methods to give you the days part, hours part, minutes part and seconds part separately so you don’t need the subtractions. See an example in my answer here.
I use this:
send start and end date in millisecond
public int GetDifference(long start,long end){
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(start);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int min = cal.get(Calendar.MINUTE);
long t=(23-hour)*3600000+(59-min)*60000;
t=start+t;
int diff=0;
if(end>t){
diff=(int)((end-t)/ TimeUnit.DAYS.toMillis(1))+1;
}
return diff;
}
You can calculate the difference in time in miliseconds using this method and get the outputs in seconds, minutes, hours, days, months and years.
You can download class from here: DateTimeDifference GitHub Link
Simple to use
long currentTime = System.currentTimeMillis();
long previousTime = (System.currentTimeMillis() - 864000000); //10 days ago
Log.d("DateTime: ", "Difference With Second: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.SECOND));
Log.d("DateTime: ", "Difference With Minute: " + AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE));
You can compare the example below
if(AppUtility.DateTimeDifference(currentTime, previousTime, AppUtility.TimeDifference.MINUTE) > 100){
Log.d("DateTime: ", "There are more than 100 minutes difference between two dates.");
}else{
Log.d("DateTime: ", "There are no more than 100 minutes difference between two dates.");
}
Try this out.
int day = 0;
int hh = 0;
int mm = 0;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy 'at' hh:mm aa");
Date oldDate = dateFormat.parse(oldTime);
Date cDate = new Date();
Long timeDiff = cDate.getTime() - oldDate.getTime();
day = (int) TimeUnit.MILLISECONDS.toDays(timeDiff);
hh = (int) (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day));
mm = (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
} catch (ParseException e) {
e.printStackTrace();
}
if (mm <= 60 && hh!= 0) {
if (hh <= 60 && day != 0) {
return day + " DAYS AGO";
} else {
return hh + " HOUR AGO";
}
} else {
return mm + " MIN AGO";
}
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, Locale);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, Locale);
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
it returns how many days between given two dates, where DateTime is from joda library
I arranged a little. This works great.
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
Date date = new Date();
String dateOfDay = simpleDateFormat.format(date);
String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();
#SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
try {
Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);
printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
#SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate) {
//milliseconds
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}
Here's the simple solution:
fun printDaysBetweenTwoDates(): Int {
val dateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH)
val endDateInMilliSeconds = dateFormat.parse("26-02-2022")?.time ?: 0
val startDateInMilliSeconds = dateFormat.parse("18-02-2022")?.time ?: 0
return getNumberOfDaysBetweenDates(startDateInMilliSeconds, endDateInMilliSeconds)
}
private fun getNumberOfDaysBetweenDates(
startDateInMilliSeconds: Long,
endDateInMilliSeconds: Long
): Int {
val difference = (endDateInMilliSeconds - startDateInMilliSeconds) / (1000 * 60 * 60 * 24).toDouble()
val noOfDays = Math.ceil(difference)
return (noOfDays).toInt()
}
When you use Date() to calculate the difference in hours is necessary configure the SimpleDateFormat() in UTC otherwise you get one hour error due to Daylight SavingTime.
You can generalize this into a function that lets you choose the output format
private String substractDates(Date date1, Date date2, SimpleDateFormat format) {
long restDatesinMillis = date1.getTime()-date2.getTime();
Date restdate = new Date(restDatesinMillis);
return format.format(restdate);
}
Now is a simple function call like this, difference in hours, minutes and seconds:
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date1 = formater.parse(dateEnd);
Date date2 = formater.parse(dateInit);
String result = substractDates(date1, date2, new SimpleDateFormat("HH:mm:ss"));
txtTime.setText(result);
} catch (ParseException e) {
e.printStackTrace();
}

Issue with formatting time duaration

Running the following code:
private static String formatDuration(final long duration) {
final long hh = duration / 1000 / 3600;
final long mm = duration / 1000 % 3600 / 60;
final long ss = duration / 1000 % 3600 % 60;
return hh + "h" + ":" + mm + "m" + ":" + ss + "s";
}
private static void printDuartion() throws ParseException{
SimpleDateFormat PARSE_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
long dayFrom = PARSE_FORMAT.parse("11/02/2014 00:00:00").getTime();
long dayTo = PARSE_FORMAT.parse("11/03/2014 23:59:59").getTime();
System.out.println(formatDuration(dayTo-dayFrom));
}
I have the an output:
48h:59m:59s
But actually it should be:
47h:59m:59s
Please help me find out where the mistake is.
Your code is correct, I also get 47h:59m:59s. Demo: http://ideone.com/fxZKba
I can only imagine that you are in a time zone where these days are affected by Daylight saving time. Like "Atlantic/Bermuda" in the following example:
private static void printDuration() throws Exception {
SimpleDateFormat PARSE_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
PARSE_FORMAT.setTimeZone(TimeZone.getTimeZone("Atlantic/Bermuda"));
long dayFrom = PARSE_FORMAT.parse("11/02/2014 00:00:00").getTime();
long dayTo = PARSE_FORMAT.parse("11/03/2014 23:59:59").getTime();
System.out.println(formatDuration(dayTo - dayFrom));
}
In this case I get 48h:59m:59s Demo: http://ideone.com/jQ7sX2

Given first chrono time, calculate value of next results given the gaps

I have some sports time results returned by an xml feed.
Result time for the first arrived is returned and converted like this:
String time = "00:01:00:440";
String gap = "";
for the other partecipants I get back only the gap:
String time = "";
String gap = "00:00:00:900";
How can I calculate the time of others partecipants given the gap from the first?
I have tried with java Date object but it uses calendar days too and I get strange result:
String firstTime = "00:01:00:440";
String gapOne = "00:00:00:900";
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss:SSS");
Date d1 = null;
Date d2 = null;
long diff = 0;
String timeResult = "";
try {
d1 = formatter.parse(firstTime);
d2 = formatter.parse(gapOne);
diff = d2.getTime() + d1.getTime();
timeResult = formatter.format(new Date(diff));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(timeResult);
But prints out:
11:01:01:340
I came up with this solution:
String firstTime = "00:01:00:440";
String gapOne = "00:00:00:900";
String firstTimeSplit[] = firstTime.split(":");
String gapSplit[] = gapOne.split(":");
int millisecSum = Integer.parseInt(firstTimeSplit[3]) + Integer.parseInt(gapSplit[3]);
int secsSum = Integer.parseInt(firstTimeSplit[2]) + Integer.parseInt(gapSplit[2]);
int minSum = Integer.parseInt(firstTimeSplit[1]) + Integer.parseInt(gapSplit[1]);
int hrsSum = Integer.parseInt(firstTimeSplit[0]) + Integer.parseInt(gapSplit[0]);
String millisec = String.format("%03d", millisecSum % 1000);
int mathSec = millisecSum / 1000 + secsSum;
String secs = String.format("%02d", mathSec % 60);
int mathMins = mathSec / 60 + minSum;
String mins = String.format("%02d", mathMins % 60);
int mathHrs = mathMins / 60 + hrsSum;
String hrs = String.format("%02d", mathHrs % 60);
String format = "%s:%s:%s:%s";
String result = String.format(format, hrs, mins, secs, millisec);
This way I get returned the value this way:
00:01:01:340

Calculate Difference between two times in Android

I have two string variables such as StartTime and EndTime. I need to Calculate the TotalTime by subtracting the EndTime with StartTime.
The Format of StartTime and EndTime is as like follows:
StartTime = "08:00 AM";
EndTime = "04:00 PM";
TotalTime in Hours and Mins Format. How to calculate this in Android?
Try below code.
// suppose time format is into ("hh:mm a") format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm a");
date1 = simpleDateFormat.parse("08:00 AM");
date2 = simpleDateFormat.parse("04:00 PM");
long difference = date2.getTime() - date1.getTime();
days = (int) (difference / (1000*60*60*24));
hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60));
min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
hours = (hours < 0 ? -hours : hours);
Log.i("======= Hours"," :: "+hours);
Output - Hours :: 8
Note: Corrected code as below which provide by Chirag Raval because in code which Chirag provided had some issues when we try to find time from 22:00 to 07:00.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
Date startDate = simpleDateFormat.parse("22:00");
Date endDate = simpleDateFormat.parse("07:00");
long difference = endDate.getTime() - startDate.getTime();
if(difference<0)
{
Date dateMax = simpleDateFormat.parse("24:00");
Date dateMin = simpleDateFormat.parse("00:00");
difference=(dateMax.getTime() -startDate.getTime() )+(endDate.getTime()-dateMin.getTime());
}
int days = (int) (difference / (1000*60*60*24));
int hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60));
int min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
Log.i("log_tag","Hours: "+hours+", Mins: "+min);
Result will be: Hours: 9, Mins: 0
Have a look at DateFormat, you can use it to parse your strings with the parse(String source) method and the you can easily manipulate the two Dates object to obtain what you want.
DateFormat df = DateFormat.getInstance();
Date date1 = df.parse(string1);
Date date2 = df.parse(string2);
long difference = date1.getTime() - date2.getTime();
days = (int) (difference / (1000*60*60*24));
hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60));
min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);
String diffHours = df.format(hours);
For date difference
Date myDate = new Date(difference);
The to show the Date :
String diff = df.format(myDate);
Please try this....
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
try {
date1 = simpleDateFormat.parse("08:00 AM");
} catch (ParseException e) {
e.printStackTrace();
}
try {
date2 = simpleDateFormat.parse("04:00 PM");
} catch (ParseException e) {
e.printStackTrace();
}
long difference = date2.getTime() - date1.getTime();
int days = (int) (difference / (1000 * 60 * 60 * 24));
int hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
int min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours))
/ (1000 * 60);
hours = (hours < 0 ? -hours : hours);
Log.i("======= Hours", " :: " + hours);
I should like to contribute the modern answer.
java.time and ThreeTenABP
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
String startTime = "08:00 AM";
String endTime = "04:00 PM";
LocalTime start = LocalTime.parse(startTime, timeFormatter);
LocalTime end = LocalTime.parse(endTime, timeFormatter);
Duration diff = Duration.between(start, end);
long hours = diff.toHours();
long minutes = diff.minusHours(hours).toMinutes();
String totalTimeString = String.format("%02d:%02d", hours, minutes);
System.out.println("TotalTime in Hours and Mins Format is " + totalTimeString);
The output from this snippet is:
TotalTime in Hours and Mins Format is 08:00
(Tested on Java 1.7.0_67 with ThreeTen Backport.)
The datetime classes used in the other answers — SimpleDateFormat, Date, DateFormat and Calendar — are all long outdated and poorly designed. Possibly worse, one answer is parsing and calculating “by hand”, without aid from any library classes. That is complicated and error-prone and never recommended. Instead I am using java.time, the modern Java date and time API. It is so much nicer to work with.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages: org.threeten.bp.Duration, org.threeten.bp.LocalTime and org.threeten.bp.format.DateTimeFormatter.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
String mStrDifferenceTime =compareTwoTimeAMPM("11:06 PM","05:07 AM");
Log.e("App---Time ", mStrDifferenceTime+" Minutes");
public static String getCurrentDateUsingCalendar() {
Date mDate = new Date(); // to get the date
#SuppressLint("SimpleDateFormat") SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("dd-MM-yyyy"); // getting date in this format
return mSimpleDateFormat.format(mDate.getTime());
}
public static String getNextDateUsingCalendar() {
Calendar mCalendar = Calendar.getInstance();
mCalendar.add(Calendar.DAY_OF_YEAR, 1);
Date mStrTomorrow = mCalendar.getTime();
#SuppressLint("SimpleDateFormat") DateFormat mDateFormat = new SimpleDateFormat("dd-MM-yyyy");
return mDateFormat.format(mStrTomorrow);
}
public static String compareTwoTimeAMPM(String mStrStartTime, String mStrEndTime) {
String mStrCompareStartTime[] = mStrStartTime.split(" ");
String mStrCompareEndTime[] = mStrEndTime.split(" ");
int mIStartTime = Integer.parseInt(mStrCompareStartTime[0].replace(":", ""));
int mIEndTime = Integer.parseInt(mStrCompareEndTime[0].replace(":", ""));
String mStrToday = "";
String mStrTomorrow = "";
if (mIStartTime < mIEndTime && mStrCompareStartTime[1].equals("PM") && mStrCompareEndTime[1].equals("PM")) {
mStrToday = getCurrentDateUsingCalendar();
mStrTomorrow = getCurrentDateUsingCalendar();
} else if (mIStartTime < mIEndTime && mStrCompareStartTime[1].equals("AM") && mStrCompareEndTime[1].equals("AM")) {
mStrToday = getCurrentDateUsingCalendar();
mStrTomorrow = getCurrentDateUsingCalendar();
} else if (mIStartTime > mIEndTime && mStrCompareStartTime[1].equals("PM") && mStrCompareEndTime[1].equals("PM")) {
String mStrTime12[] = mStrCompareStartTime[0].split(":");
if (mStrTime12[0].equals("12")) {
mStrToday = getNextDateUsingCalendar();
mStrTomorrow = getNextDateUsingCalendar();
} else {
mStrToday = getCurrentDateUsingCalendar();
mStrTomorrow = getNextDateUsingCalendar();
}
} else if (mIStartTime > mIEndTime && mStrCompareStartTime[1].equals("AM") && mStrCompareEndTime[1].equals("AM")) {
String mStrTime12[] = mStrCompareStartTime[0].split(":");
if (mStrTime12[0].equals("12")) {
mStrToday = getNextDateUsingCalendar();
mStrTomorrow = getNextDateUsingCalendar();
} else {
mStrToday = getCurrentDateUsingCalendar();
mStrTomorrow = getNextDateUsingCalendar();
}
} else if (mStrCompareStartTime[1].equals("PM") && mStrCompareEndTime[1].equals("AM")) {
mStrToday = getCurrentDateUsingCalendar();
mStrTomorrow = getNextDateUsingCalendar();
} else if (mStrCompareStartTime[1].equals("AM") && mStrCompareEndTime[1].equals("PM")) {
mStrToday = getCurrentDateUsingCalendar();
mStrTomorrow = getCurrentDateUsingCalendar();
}
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm aa");
String mStrDifference = "";
try {
Date date1 = simpleDateFormat.parse(mStrToday + " " + mStrStartTime);
Date date2 = simpleDateFormat.parse(mStrTomorrow + " " + mStrEndTime);
mStrDifference = differenceDatesAndTime(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
return mStrDifference;
}
public static String differenceDatesAndTime(Date mDateStart, Date mDateEnd) {
long different = mDateEnd.getTime() - mDateStart.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
long minutes = elapsedHours * 60 + elapsedMinutes;
long result = elapsedDays * 24 * 60 + minutes;
if (0 > result) {
result = result + 720; //result is minus then add 12*60 minutes
}
return result + "";
}
My output is E/App---Time: 361 Minutes
Try simple piece of code using For 24 hour time
StartTime = "10:00";
EndTime = "13:00";
here starthour=10 and end hour=13
if(TextUtils.isEmpty(txtDate.getText().toString())||TextUtils.isEmpty(txtDate1.getText().toString())||TextUtils.isEmpty(txtTime.getText().toString())||TextUtils.isEmpty(txtTime1.getText().toString()))
{
Toast.makeText(getApplicationContext(), "Date/Time fields cannot be blank", Toast.LENGTH_SHORT).show();
}
else {
if (starthour > endhour) {
Toast.makeText(getApplicationContext(), "Start Time Should Be Less Than End Time", Toast.LENGTH_SHORT).show();
} else if (starthour == endhour) {
if (startmin > endmin) {
Toast.makeText(getApplicationContext(), "Start Time Should Be Less Than End Time", Toast.LENGTH_SHORT).show();
}
else{
tvalid = "True";
}
} else {
// Toast.makeText(getApplicationContext(),"Sucess"+(endhour-starthour)+(endmin-startmin),Toast.LENGTH_SHORT).show();
tvalid = "True";
}
}
same for date also

Categories