I want return millisecond to time
But my code not work !
long ms = 86400000;
long s = ms % 60;
long m = (ms / 60) % 60;
long h = (ms / (60 * 60)) % 24;
String timeFind = String.format("%d:%02d:%02d", h, m, s);
You could use SimpleDateFormat, but be aware that you should set both the time zone and the locale appropriately:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss", Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String text = formatter.format(new Date(millis));
The time zone part is important, as otherwise it will use the system-default time zone, which would usually be inappropriate. Note that the Date here will be on January 1st 1970, UTC - assuming your millisecond value is less than 24 hours.
You can use
int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
1 second= 1000 milli seconds... Try now
or if you are trying to retrive the current time you could use Calendar class
Calendar cal = Calendar.getInstance();
String time =""+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE);
Use TimeUnit instead of do all that math, that way you make sure that this will actually work, and It's more readable.
Use my code simple and work for me
just call this function and put millisecond
public String settIMER(int time) {
String str = "00:00";
try {
long parseLong = time;
if (parseLong >= 3600000) {
try {
str = String.format(Locale.getDefault(), "%02d:%02d:%02d",
new Object[]{Long.valueOf(TimeUnit.MILLISECONDS.toHours(parseLong)),
Long.valueOf(TimeUnit.MILLISECONDS.toMinutes(parseLong) % TimeUnit.HOURS.toMinutes(1)),
Long.valueOf(TimeUnit.MILLISECONDS.toSeconds(parseLong) % TimeUnit.MINUTES.toSeconds(1))});
} catch (NumberFormatException unused) {
java.lang.System.out.println(parseLong);
}
} else {
str = String.format(Locale.getDefault(), "%02d:%02d",
new Object[]{Long.valueOf(TimeUnit.MILLISECONDS.toMinutes(parseLong) % TimeUnit.HOURS.toMinutes(1)),
Long.valueOf(TimeUnit.MILLISECONDS.toSeconds(parseLong) % TimeUnit.MINUTES.toSeconds(1))});
}
return str;
} catch (Exception e) {
return "00:00";
}
}
Related
I am saving Current Date time as Timestamp with below code in my Android
userValues.put("rTime", ServerValue.TIMESTAMP);
Now I want to calculate difference as
String posttime=1576917051506 //retrieve saved timestamp
String currenttime=ServerValue.TIMESTAMP //current time
difference=1hour 25 minutes
how can i achieve this
String posttime=1576917051506
String currenttime=ServerValue.TIMESTAMP
first of all convert times to Long
long time1 = Long.valueof(posttime)
long time2 = Long.valueof(currenttime)
long diffrence = time2-time1
String myValue = convertSecondsToHMmSs(diffrence)
Now myValue is your time diffrence. like 1h:2m
public static String convertSecondsToHMmSs(long millis) {
long seconds = (millis / 1000) % 60;
long minutes = (millis / (1000 * 60)) % 60;
long hours = millis / (1000 * 60 * 60);
StringBuilder b = new StringBuilder();
b.append(hours == 0 ? "00" : hours < 10 ? String.valueOf("0" + hours) :
String.valueOf(hours));
b.append(":");
b.append(minutes == 0 ? "00" : minutes < 10 ? String.valueOf("0" + minutes) :
String.valueOf(minutes));
b.append(":");
b.append(seconds == 0 ? "00" : seconds < 10 ? String.valueOf("0" + seconds) :
String.valueOf(seconds));
return b.toString();
}
Using Joda time:
DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
long hours = p.getHours();
long minutes = p.getMinutes();
How to get difference between two dates in Days, Hours (24), Minutes (60), Seconds(60).
and
I have been go through
Android difference between Two Dates
How do I get difference between two dates in android?, tried every thing and post
but no help,
Here is my code..
try {
String FinalDate = "20-04-2018 08:00:00";
String CurrentDate = "26-04-2018 10:10:30";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
/*long difference = date1.getTime() - date2.getTime();
long differenceInMinutes = difference / (60 * 1000);
long differenceInSeconds = difference / 1000;
String strMinuteDifference = Long.toString(differenceInMinutes);
String strSecondsDifference = Long.toString(differenceInSeconds);*/
long difference = date1.getTime() - date2.getTime();
long seconds = difference / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
Log.e("TAG_5", "CurrentDate is : " + date1);
Log.e("TAG_5", "Final date is : " + date2);
Log.e("TAG_5", "Day Difference: " + days);
Log.e("TAG_5", "hours Difference: " + hours);
Log.e("TAG_5", "Minute Difference: " + minutes);
Log.e("TAG_5", "Seconds Difference: " + seconds);
} catch (Exception exception) {
Log.e("TAG_5", "exception " + exception);
}
and the output is
E/TAG_5: CurrentDate is : Thu Apr 26 10:10:30 GMT+05:30 2018
E/TAG_5: Demo date is : Fri Apr 20 08:00:00 GMT+05:30 2018
E/TAG_5: Day Difference: 6
E/TAG_5: hours Difference: 146
E/TAG_5: Minute Difference: 8770
E/TAG_5: Seconds Difference: 526230
Its seems be like the code is Calculate All the Hours, Minutes, Seconds between those two dates but
I want Output be like...
Hours should be like 2 hours, 10 hours or 23 hours but not more than 24, because 25 hours will be new day so that should be 1 Day and 1 hour.
and Minutes be like 10 minutes 35 minutes or 59 minutes, but not more than 60
same goes for Seconds, it should be 12 seconds, 40 seconds or 59 seconds but not more than 60.
So how can i achieve this ?
To calculate the "rest" hours like you said. (So below 24 hours) you can use modulo.
In computing, the modulo operation finds the remainder after division
of one number by another (sometimes called modulus).
int hours = theAmountOfHours % 24
In your example
Log.e("TAG_5", "Day Difference: " + days);
Log.e("TAG_5", "hours Difference: " + hours % 24);
Log.e("TAG_5", "Minute Difference: " + minutes % 60);
Log.e("TAG_5", "Seconds Difference: " + seconds % 60);
Sources: Wikipedia
Try this method
public void printDifferenceDateForHours(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;
//TODO Here you will get the days
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
//TODO Here you will get the hours
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
//TODO Here you will get the minute
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
//TODO Here you will get the second
long elapsedSeconds = different / secondsInMilli;
}
try {
String FinalDate = "20-04-2018 08:00:00";
String CurrentDate = "26-04-2018 10:10:30";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
long seconds = 1000;
long minutes = 60 * seconds;
long hours = 60 * minutes;
long days = 24 * hours;
long weeks = 7 * days;
long months = 30 * days;
long year = 365 * days;
long difference = date1.getTime() - date2.getTime();
long differenceInDays = difference / days;
difference = difference - (differenceInDays * days);
long differenceInHours = (difference) / hours;
difference = difference - (differenceInHours * hours);
long differenceInMin = (difference) / minutes;
difference = difference - (differenceInMin * minutes);
long differenceInSecond = difference / seconds;
Log.e("TAG_5", "CurrentDate is : " + date1);
Log.e("TAG_5", "Final date is : " + date2);
Log.e("TAG_5", "Day Difference: " + differenceInDays);
Log.e("TAG_5", "hours Difference: " + differenceInHours);
Log.e("TAG_5", "Minute Difference: " + differenceInMin);
Log.e("TAG_5", "Seconds Difference: " + differenceInSecond);
} catch (Exception exception) {
Log.e("TAG_5", "exception " + exception);
}
Here i have calculated only day,month,min,second you can calculate year,month,week same way
You can use epoch time (unix timestamp) of both the dates and calculate the days, hours, mins and sms difference yourself using the modulo (% - remainder) operator.
You can do this way, I hope it help for you. thanks
String CurrentDate = "26-04-2018 10:10:30";
String FinalDate = "20-04-2018 08:00:00";
long diffInMillisec = CurrentDate.getTime() - FinalDate.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMillisec);
seconds = diffInSec % 60;
diffInSec/= 60;
minutes =diffInSec % 60;
diffInSec /= 60;
hours = diffInSec % 24;
diffInSec /= 24;
days = diffInSec;`
1.Divide the difference by days to get number of days/hours/minutes/etc.
2.perform Modulo to get the remaining seconds.
Use
long difference="your difference result here";
long seconds =1000;
long minutes =60*seconds;
long hours = 60*minutes;
long days = 24*hours;
long weeks=7*days;
long months=30*days;
long year=365*days;
if(difference>year) {
Log.d("year", String.valueOf(difference / year));
difference = difference % year;
}
if(difference>months) {
Log.d("months", String.valueOf(difference / months));
difference = difference % months;
}
if(difference>weeks) {
Log.d("weeks", String.valueOf(difference / weeks));
difference = difference % weeks;
}
if(difference>days) {
Log.d("days", String.valueOf(difference / days));
difference = difference % days;
}
if(difference>hours) {
Log.d("hours", String.valueOf(difference / hours));
difference = difference % hours;
}
if(difference>minutes) {
Log.d("minutes", String.valueOf(difference / minutes));
difference = difference % minutes;
}
if(difference>0)
Log.d("seconds", String.valueOf(difference/seconds ));
I need to get Day Hours Minutes to reach certain date
example :
Date = "14-08-2015 16:38:28"
Current_Date = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date());
and to reach that Date the result will be
2 Days and 1 hour and 30 minutes
Simple searching on google I got
String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 10:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
see below links
http://www.mkyong.com/java/how-to-calculate-date-time-difference-in-java/
How to find the duration of difference between two dates in java?
Calculate date/time difference in java
You could use:
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
There are plenty of constants in Calendar for everything you need. Edit: Calendar class documentation
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();
}
I want to display the difference between two times in hh:mm format.
The first time is from a database and the second time is the system time. Time difference is updated every second.
How can I do that?
Currently I'm using two manual time if this works perfectly then I implement it into my apps.
public class MainActivity extends Activity
{
TextView mytext;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Timer updateTimer = new Timer();
updateTimer.schedule(new TimerTask()
{
public void run()
{
try
{
TextView txtCurrentTime= (TextView)findViewById(R.id.mytext);
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
Date date1 = format.parse("08:00:12 pm");
Date date2 = format.parse("05:30:12 pm");
long mills = date1.getTime() - date2.getTime();
Log.v("Data1", ""+date1.getTime());
Log.v("Data2", ""+date2.getTime());
int hours = (int) (mills/(1000 * 60 * 60));
int mins = (int) (mills % (1000*60*60));
String diff = hours + ":" + mins; // updated value every1 second
txtCurrentTime.setText(diff);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}, 0, 1000);
}
}
To Calculate the difference between two dates you could try something like:
long millis = date1.getTime() - date2.getTime();
int hours = (int) (millis / (1000 * 60 * 60));
int mins = (int) ((millis / (1000 * 60)) % 60);
String diff = hours + ":" + mins;
To update the Time Difference every second you can make use of Timer.
Timer updateTimer = new Timer();
updateTimer.schedule(new TimerTask() {
public void run() {
try {
long mills = date1.getTime() - date2.getTime();
int hours = millis/(1000 * 60 * 60);
int mins = (mills/(1000*60)) % 60;
String diff = hours + ":" + mins; // updated value every1 second
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0, 1000); // here 1000 means 1000 mills i.e. 1 second
Edit : Working Code :
public class MainActivity extends Activity {
private TextView txtCurrentTime;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtCurrentTime= (TextView)findViewById(R.id.mytext);
Timer updateTimer = new Timer();
updateTimer.schedule(new TimerTask()
{
public void run()
{
try
{
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss aa");
Date date1 = format.parse("08:00:12 pm");
Date date2 = format.parse("05:30:12 pm");
long mills = date1.getTime() - date2.getTime();
Log.v("Data1", ""+date1.getTime());
Log.v("Data2", ""+date2.getTime());
int hours = (int) (mills/(1000 * 60 * 60));
int mins = (int) (mills/(1000*60)) % 60;
String diff = hours + ":" + mins; // updated value every1 second
txtCurrentTime.setText(diff);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}, 0, 1000);
}
finally did it yuppiiieee ...
package com.timedynamicllyupdate;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity
{
TextView current;
private TextView txtCurrentTime;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread myThread = null;
Runnable myRunnableThread = new CountDownRunner();
myThread= new Thread(myRunnableThread);
myThread.start();
current= (TextView)findViewById(R.id.current);
}
public void doWork()
{
runOnUiThread(new Runnable()
{
public void run()
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss aa");
txtCurrentTime= (TextView)findViewById(R.id.mytext);
Date systemDate = Calendar.getInstance().getTime();
String myDate = sdf.format(systemDate);
// txtCurrentTime.setText(myDate);
Date Date1 = sdf.parse(myDate);
Date Date2 = sdf.parse("02:50:00 pm");
long millse = Date1.getTime() - Date2.getTime();
long mills = Math.abs(millse);
int Hours = (int) (mills/(1000 * 60 * 60));
int Mins = (int) (mills/(1000*60)) % 60;
long Secs = (int) (mills / 1000) % 60;
String diff = Hours + ":" + Mins + ":" + Secs; // updated value every1 second
current.setText(diff);
}
catch (Exception e)
{
}
}
});
}
class CountDownRunner implements Runnable
{
// #Override
public void run()
{
while(!Thread.currentThread().isInterrupted())
{
try
{
doWork();
Thread.sleep(1000); // Pause of 1 Second
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
catch(Exception e)
{
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Using java.time
The modern way is with the java.time classes that supplant the troublesome old date-time classes.
The LocalTime class represents a time-of-day without a date and without a time zone.
Define a formatting pattern with DateTimeFormatter class.
String inputStart = "08:00:12 pm".toUpperCase() ;
String inputStop = "05:30:12 pm".toUpperCase() ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "hh:mm:ss a" );
LocalTime start = LocalTime.parse( inputStart , f );
LocalTime stop = LocalTime.parse( inputStop , f );
start.toString(): 20:00:12
stop.toString(): 17:30:12
The LocalTime class works within a single generic 24-hour day. So it does not consider crossing midnight. If you want to cross over between days you should be using ZonedDateTime, OffsetDateTime, or LocalDateTime instead, all date-time objects rather than time-of-day-only.
A Duration captures a span of time unattached to the timeline.
Duration d = Duration.between( start , stop );
Calling toString generates text in the standard ISO 8601 format for durations: PnYnMnDTnHnMnS where the P marks the beginning and the T separates the years-months-days from the hours-minutes-seconds. I strongly recommend using this format rather than "HH:MM:SS" format that is ambiguous with clock-time.
If you insist on using the ambiguous clock-time format, in Java 9 and later you can build that string by calling toHoursPart, toMinutesPart, and toSecondsPart.
In your example data we are moving backwards in time, going from 8 PM to 5 PM, so the result is a negative number of hours and minutes, a negative two and a half hours.
d.toString(): PT-2H-30M
See this code run live at IdeOne.com.
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, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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.
OK I Build here Funcion for you:
public void omriFunction(){
Date Start = null;
Date End = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
try {
Start = simpleDateFormat.parse(04+":"+30);
End = simpleDateFormat.parse(06+":"+45);}
catch(ParseException e){
//Some thing if its not working
}
long difference = End.getTime() - Start.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);
if(hours < 0){
hours+=24;
}if(min < 0){
float newone = (float)min/60 ;
min +=60;
hours =(int) (hours +newone);}
String c = hours+":"+min;
Log.d("ANSWER",c);}
ANSWER :2:15; in the logcat
The process is roughly as follows,
Convert your string instance to a date instance the following way
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2011-01-03");
Assuming the systemTime you have is a long, representing miliseconds since the epoc, you can now do the following
long difference = longNow - date.getTime();
int msPerHour = 1000*60*60;
int hours = difference/secondPerHour;
int minutes = difference % secondPerHour;
where longNow is your current variable containing system time.
Date currentTime = parseDate("11:27:20 AM");
Date endTime = parseDate("10:30:01 AM");
if (endTime.before(currentTime))
{
Log.e("Time :","===> is before from current time");
}
if (endTime.after(currentTime))
{
Log.e("Time :","===> is after from current time");
}
private Date parseDate(String date)
{
String inputFormat = "hh:mm:ss aa";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
Hi Guys not sure what I was doing wrong , but this helped for me , hope I can help someone else out.
My min were being calculated in some float format so I used this formula
long Min = time % (1000*60*60)/(60*1000);
time is my date2.getTime() - date1.getTime();
Happy coding
Tray The following code to get hour and minute different between two times:
private static int getHoursDiff(Calendar c1, Calendar c2) {
Date d1 = c1.getTime();
Date d2 = c2.getTime();
long mils = d1.getTime() - d2.getTime();
int hourDiff = (int) (mils / (1000 * 60 * 60));
return hourDiff;
}
private static int getMinuteDiff(Calendar c1, Calendar c2) {
Date d1 = c1.getTime();
Date d2 = c2.getTime();
long mils = d1.getTime() - d2.getTime();
int minuteFor = (int) (mils / (1000 * 60) % 60);
return minuteFor;
} }
So I was hunting around for a way where I could get HH/MM/SS from 2 Times in Kolin and this seems like a nice way to do it.
It uses import org.threeten.bp
fun getTimedifference(startTime: LocalDateTime, endTime: LocalDateTime): String {
val startTimeInstant = startTime.atOffset(ZoneOffset.UTC).toInstant()
val endTimeInstant = endTime.atOffset(ZoneOffset.UTC).toInstant()
val duration = Duration.between(startTimeInstant, endTimeInstant)
val days = duration.toDays()
val hours = duration.toHours() - (days * 24)
val min = duration.toMinutes() - (duration.toHours() * 60)
val sec = (duration.toMillis() / 1000) - (duration.toMinutes() * 60)
return "${hours}:${min}:${sec}"
}
try this function, if you want correct time diff you must add timezone in it, this is a normal mistake.
fun main() {
val format = "MM/dd/yyyy hh:mm:ss aa"
val cal = Calendar.getInstance()
val sdf = SimpleDateFormat(format, Locale.getDefault())
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Karachi")) //make sure to set timezone
val arrivedDate = "03/15/2022 12:00:00 PM"
val currentDate = sdf.format(cal.timeInMillis)
print("Arrived time: " + arrivedDate + "\n")
print("Current time: " + currentDate + "\n")
val arrivedDateMillis = getLongDateFromString(arrivedDate, sdf)
val currentDateMillis = getLongDateFromString(currentDate, sdf)
val diff = (currentDateMillis - arrivedDateMillis) / 1000
val p1 = diff % 60
var p2 = diff / 60
val p3 = p2 % 60
val p4 = diff / 60 / 60 / 24
p2 = p2 / 60 % 24
print("$p4:$p2:$p3:$p1") //days:hours:minutes:seconds
}
fun getLongDateFromString(time: String, format: SimpleDateFormat): Long {
try {
val date = format.parse(time)
return date.time
} catch (e: Exception) {
e.printStackTrace()
}
return 0L
}