I am developing and android app, where I need to calculate the difference between two times.I need to calculate the time difference for 24 hrs, and also the difference between times on two days(Eg. 5pm today to 9 am tomorrow).
I have tried the below code, to calculate the difference which works only for 24 hrs,
String dateStart = "08:00:00";
String dateStop = "13:00:00";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("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 diffHours = diff / (60 * 60 * 1000) % 24;
Log.e("test",diffHours + " hours, ");
}
catch (Exception e)
{
// TODO: handle exception
}
Sir, you can make it easily in using java feature. long difference = date2.getTime() - date1.getTime(); Take a look in this link this will help you.
Correct way to find proper time difference:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
Date startDate = simpleDateFormat.parse("22:00:59");
Date endDate = simpleDateFormat.parse("23:00:10");
long difference = endDate.getTime() - startDate.getTime();
if(difference<0)
{
Date dateMax = simpleDateFormat.parse("24:00:00");
Date dateMin = simpleDateFormat.parse("00: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);
int sec = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours) - (1000*60*min)) / (1000);
Log.i("log_tag","Hours: "+hours+", Mins: "+min+", Secs: "+sec);
Result will be: Hours: 0, Mins: 59, Secs: 11
tl;dr
ChronoUnit.HOURS.between(
LocalTime.parse( "08:00:00" ) ,
LocalTime.parse( "13:00:00" )
)
5
…or…
ChronoUnit.HOURS.between(
ZonedDateTime.of(
LocalDate.of( 2017 , Month.JANUARY , 23 ) ,
LocalTime.parse( "08:00:00" ) ,
ZoneId.of( "America/Montreal" )
) ,
ZonedDateTime.of(
LocalDate.of( 2017 , Month.JANUARY , 25 ) ,
LocalTime.parse( "13:00:00" ) ,
ZoneId.of( "America/Montreal" )
)
)
53
java.time
Modern approach uses the java.time classes.
LocalTime
The LocalTime class represents a time-of-day without a date and without a time zone.
LocalTime start = LocalTime.parse( "08:00:00" ) ;
LocalTime stop = LocalTime.parse( "13:00:00" ) ;
Duration
Get a Duration object to represent the span-of-time.
Duration d = Duration.between( start , stop ) ;
ChronoUnit
For number of hours, use ChronoUnit.
long hours = ChronoUnit.HOURS.between( start , stop ) ;
Android
For Android, see the ThreeTen-Backport and ThreeTenABP projects. See last bullets below.
ZonedDateTime
If you want to cross days, going past midnight, you must assign dates and time zones.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime start = ZonedDateTime.of(
LocalDate.of( 2017 , Month.JANUARY , 23 ) ,
LocalTime.parse( "08:00:00" ) ,
z
) ;
ZonedDateTime stop = ZonedDateTime.of(
LocalDate.of( 2017 , Month.JANUARY , 25 ) ,
LocalTime.parse( "13:00:00" ) ,
z
) ;
long hours = ChronoUnit.HOURS.between( start , stop ) ;
See this code run live at IdeOne.com.
53
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, Java 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 Java 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….
You can try something like this also if you are sure the 9 am is next day you can add one day and calculate the difference:
String string1 = "05:00:00 PM";
Date time1 = new SimpleDateFormat("HH:mm:ss aa").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
String string2 = "09:00:00 AM";
Date time2 = new SimpleDateFormat("HH:mm:ss aa").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
Date x = calendar1.getTime();
Date xy = calendar2.getTime();
long diff = x.getTime() - xy.getTime();
diffMinutes = diff / (60 * 1000);
float diffHours = diffMinutes / 60;
System.out.println("diff hours" + diffHours);
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
I worked it out this way:
Date time1 = new SimpleDateFormat("HH:mm:ss aa").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
Date time2 = new SimpleDateFormat("HH:mm:ss aa").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
if(calendar2.get(Calendar.AM_PM) == 1 && calendar1.get(Calendar.AM_PM) == 0) {
calendar2.add(Calendar.DATE, 1);
}
long diff = calendar1.getTimeInMillis() - calendar2.getTimeInMillis()
This will help to find the difference in time round the clock.
Related
I want hours and minutes will start from the current date will be October 10, 2016 end of days
package com.mkyong.date;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDifferentExample
{
public static void main(String[] args)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//get current date time with Date()
Date date = new Date();
System.out.println(dateFormat.format(date));
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
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();
}
}
}
Results :
2016/08/15 18:54:03
2016/08/15 18:54:03
1097 Days1 Hours 1 Minute 50 Second
My want to result for example :
100 days 5 hours 2 minutes
Avoid old date-time classes
You are using troublesome old legacy date-time classes bundled with the earliest versions of Java. Use java.time classes instead.
Parsing
Your input strings are almost in standard ISO 8601 format. Replace the SPACE in the middle with a T. The java.time classes parse/generate strings using ISO 8601 formats by default. So no need to specify a formatting pattern.
String startInput = "01/14/2012 09:29:58".replace( " " , "T" );
String stopInput = "01/15/2012 10:31:48".replace( " " , "T" );
LocalDateTime
Your inputs lack any information about offset-from-UTC or time zone. So we parse as LocalDateTime objects.
LocalDateTime startLdt = LocalDateTime.parse( startInput );
LocalDateTime stopLdt = LocalDateTime.parse( stopInput );
If you work further with these types you will get results based on generic 24-hour days while ignoring anomalies such as Daylight Saving Time (DST).
If you know the context of this data is a particular time zone, apply the zone to get ZonedDateTime.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime start = startLdt.atZone( zoneId );
ZonedDateTime stop = stopLdt.atZone( zoneId );
If you want the current moment as the start or the stop, call now. Pass the desired/expected time zone rather than relying on the JVM’s current default time zone.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Duration
The Duration class represents a span of time as a total of seconds plus a fraction of a second in nanoseconds resolution.
Duration duration = Duration.between( start , stop );
Oddly, in Java 8 this class lacks methods to get the number of days, hours, etc. making up this span of time. Java 9 adds to…Part methods.
long days = duration.toDaysPart();
int hours = duration.toHoursPart();
int minutes = duration.toMinutesPart();
Until Java 9 you can do the math yourself.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in 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.
public final void set(int year,int month,int date) - this method of Calendar class can be used to set date .
public final void set(int year, int month,int date,int hourOfDay,int minute,int second) can be used to set time too.
Calendar.getInstance() by default set current date and time.`
So my method receives a time in 24 hour format ("HH:MM:SS") and returns a string the difference time. If it's 2:00PM local time I should be able to send it "16:30:00"(4:30PM) and get the output "2 hours, 30 mins". But the code has some problem, and I am just a beginner and I need help to fix it.
The problem is if the time is 4:40PM, and I sent it "17:00:00"(5:00PM) it returns the message:
12 hours, 20 minutes instead of 0 hours, 20 minutes.
The other problem is if I sent it the current time, it would return "12 hours" away, and not 24 like it should.
Please keep in mind I am only a beginner at java and math really isn't my thing, so any help is highly appreciated. Thanks.
private static String timeUntil(String distanceTime) {
String returnMsg = null;
try {
SimpleDateFormat sdfDate = new SimpleDateFormat("hh:mm:ss");
Date now = new Date();
java.text.DateFormat df = new java.text.SimpleDateFormat("hh:mm:ss");
Date date1 = df.parse(sdfDate.format(now));
Date date2 = df.parse(distanceTime);
long diff = date2.getTime() - date1.getTime();
int timeInSeconds = (int) (diff / 1000);
int hours, minutes;
hours = timeInSeconds / 3600;
timeInSeconds = timeInSeconds - (hours * 3600);
minutes = timeInSeconds / 60;
if (hours >= 0) {
returnMsg = hours + " hours" +
"\n" + minutes + " mins";
} else {
returnMsg = minutes + " mins";
}
} catch (Exception e) {
e.printStackTrace();
}
return returnMsg;
}
In your date format, hh is used for 12-hour time. Use HH for 24-hour time:
new SimpleDateFormat("HH:mm:ss");
Code review comments...
Most of the Date class' methods are deprecated. You should consider using Calendar (GregorianCalendar) instead of Date.
Your variable names often lack meaning - you have to know the purpose of the variable to know its meaning. Your code will be more maintainable if you use better variable names. df could be renamed "format" or "dateFormat".
You create a Date object 'now', then you pass it through your df DateFormat instance, hten through your sdfDate instance, to convert it back to a Date. This is unnecessary. Replace this with Date date1 = new Date(); and remove Date now = new Date();. Simiilarly, I've seen very difficult to diagnose errors when converting between units, so you should change diff to indicate that it's milliseconds, like diff_ms. And you should keep names consistent - you change from "different" (diff) to "timeInSeconds". They should both be "timeInXxx" or "diff_xx". the distanceTime parameter should be renamed something like futureTime
You do a bunch of math to determine the difference between two times, but there are libraries that will do this for you. Google for "java difference between two dates" and find many answers.
Your code always assumes that the second time occurs after "now". This should be included in a comment at the top of your method.
When you instantiate date1 and date2, they're both probably for the same day. Try debugging or at least printing the objects to stdout immediately after they're created to see if this is the case. Is this what you really want?
Your code doesn't handle leap year.
Instead of handling all of the time conversions yourself, why don't you look for a library that does it for you?
This is your fixed code. I have changed the date format to HH:mm:ss and also your calculation logic. Try it and let us know
private static String timeUntil(String distanceTime) {
String returnMsg = null;
try {
SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm:ss");
Date now = new Date();
java.text.DateFormat df = new java.text.SimpleDateFormat("HH:mm:ss");
Date date1 = df.parse(sdfDate.format(now));
Date date2 = df.parse(distanceTime);
long diff = date2.getTime() - date1.getTime();
int timeInSeconds = (int) (diff / 1000);
int hours, minutes;
hours = timeInSeconds / 3600;
timeInSeconds = timeInSeconds - (hours * 3600);
minutes = timeInSeconds / 60;
if (hours != 0) {
returnMsg = hours + " hours" +
"\n" + minutes + " mins";
} else {
returnMsg = minutes + " mins";
}
} catch (Exception e) {
e.printStackTrace();
}
return returnMsg;
}
Here is an example which is more robust and uses Java more modern date functions. I could go point by point and point at all the thing you could have done better in your example, but sometimes its easier to give you a good example and let you glean what you can from other people code as far as good style.
import java.util.Calendar;
public class testSpace {
public static void main (String ... args){
System.out.println(timeUntil("00:12:12"));
}
private static String timeUntil(String distanceTime){
String[] times = distanceTime.split(":");
Calendar now = Calendar.getInstance();
Calendar then = Calendar.getInstance();
then.set(Calendar.SECOND, Integer.parseInt(times[2]));
then.set(Calendar.MINUTE, Integer.parseInt(times[1]));
then.set(Calendar.HOUR, Integer.parseInt(times[0]) % 12);
then.set(Calendar.AM_PM, (Integer.parseInt(times[0]) >= 12 ) ? Calendar.PM : Calendar.AM);
boolean isFuture = (then.getTimeInMillis() > now.getTimeInMillis());
long interval = (isFuture)
? then.getTimeInMillis() - now.getTimeInMillis()
: now.getTimeInMillis() - then.getTimeInMillis();
return ((isFuture) ? "" : "-") + millToTime(interval);
}
public static long MILLISECOND_PER_HOUR = 1000*60*60;
public static long MILLISECOND_PER_MIN = 1000*60;
public static long MILLISECOND_PER_SECOND = 1000;
public static String millToTime(long mill){
long hours = mill / MILLISECOND_PER_HOUR;
long mins = (mill % MILLISECOND_PER_HOUR) / MILLISECOND_PER_MIN;
long sec = ((mill % MILLISECOND_PER_HOUR) % MILLISECOND_PER_MIN) / MILLISECOND_PER_SECOND;
return String.format("%d:%d:%d", hours, mins, sec);
}
}
tl;dr
For time-of-day only, without a date or time zone.
LocalTime start = LocalTime.of( "16:40" ) ;
LocalTime stop = LocalTime.of( "17:00" ) ;
Duration d = Duration.between( start , stop ) ;
PT20M
Or, for date-time in a zone.
ZoneId z = ZoneId.of( "America/Montreal" )
ZonedDateTime zdtNow = ZonedDateTime.now( z );
ZonedDateTime zdtThen =
ZonedDateTime.of( // Pass a LocalDate, LocalTime, ZoneId.
zdtNow.toLocalDate() , // Same date…
LocalTime.parse( "16:30:00" ) , // … but different time-of-day.
z
)
Duration d = Duration.between( zdtNow , zdtThen ) ;
PT2H30M
Details
You are using old date-time classes, now legacy, supplanted by the java.time classes.
LocalTime
You are incorrectly using a date-time class for a time-of-day-only value. Instead use the LocalTime class. And use a span-of-time class when calculating elapsed time.
String input = "16:30:00" ;
LocalTime lt = LocalTime.parse( input );
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now();
ZonedDateTime
Determining a wall-clock time requires a time zone. Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdtNow = instant.atZone( z ); // Adjusted into your time zone.
Now construct a ZonedDateTime for your given input time-of-day.
ZonedDateTime zdtTarget = ZonedDateTime.of( zdtNow.toLocalDate() , lt , z );
Duration
Use Duration to represent elapsed time not attached to the timeline.
Duration d = Duration.between( zdtNow , zdtTarget );
Note that the duration will be a negative amount if the specified time-of-day is earlier than the current time-of-day.
ISO 8601 string for duration
To get a String describing the hours, minutes, etc. of that span of time, simply call toString to generate a String in standard ISO 8601 format of PnYnMnDTnHnMnS where P marks the beginning and T separates the years-month-days from hours-minutes-seconds.
If the current time were 14:00:00 in the same zone, the output would be:
PT2H30M
Getter methods
Oddly, in Java 8 this class Duration lacks any getter methods for the parts such as 2 for hours and 30 for minutes. Remedied in Java 9 with methods such as toHoursPart and toMinutesPart.
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 java.time.
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….
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.
I need to do the CountDown Days from one date to the second date
e.g
CURRENT_DATE:3/1/2013 NEXT_DATE:21/01/2013
then it displays ::17 DAYS LEFT
I implemented code like these
String inputDateString = "01/22/2013";
Calendar calCurr = Calendar.getInstance();
Calendar calNext = Calendar.getInstance();
calNext.setTime(new Date(inputDateString));
if(calNext.after(calCurr))
{
long timeDiff = calNext.getTimeInMillis() - calCurr.getTimeInMillis();
int daysLeft = (int) (timeDiff/DateUtils.DAY_IN_MILLIS);
dni.setText("Days Left: "+daysLeft);
}
else
{
long timeDiff = calCurr.getTimeInMillis() - calNext.getTimeInMillis();
timeDiff = DateUtils.YEAR_IN_MILLIS - timeDiff;
int daysLeft = (int) (timeDiff/DateUtils.DAY_IN_MILLIS);
}
Is there a better way to do achieve these?
Using Calendar's Methods:
String inputDateString = "01/22/2013";
Calendar calCurr = Calendar.getInstance();
Calendar day = Calendar.getInstance();
day.setTime(new SimpleDateFormat("MM/dd/yyyy").parse(inputDateString));
if(day.after(calCurr)){
System.out.println("Days Left: " + (day.get(Calendar.DAY_OF_MONTH) -(calCurr.get(Calendar.DAY_OF_MONTH))) );
}
Output: Days Left: 17
And to increment the year by 1 , you could use Calendar.add() method
day.add(Calendar.YEAR, 1);
There are several libraries to convert date to n days format:
PrettyTime
JodaTime
I use this class
import android.text.format.DateUtils;
import java.util.Date;
import static android.text.format.DateUtils.FORMAT_NUMERIC_DATE;
import static android.text.format.DateUtils.FORMAT_SHOW_DATE;
import static android.text.format.DateUtils.FORMAT_SHOW_YEAR;
import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
/**
* Utilities for dealing with dates and times
*/
public class TimeUtils {
/**
* Get relative time for date
*
* #param date
* #return relative time
*/
public static CharSequence getRelativeTime(final Date date) {
long now = System.currentTimeMillis();
if (Math.abs(now - date.getTime()) > 60000)
return DateUtils.getRelativeTimeSpanString(date.getTime(), now,
MINUTE_IN_MILLIS, FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR
| FORMAT_NUMERIC_DATE);
else
return "Just now";
}
}
TimeUtils.getRelativeTime(date) returns text like
Just now,
2 min. ago,
2 hours ago,
2 days ago,
04.11.2013
tl;dr
java.time.temporal.ChronoUnit.DAYS.between(
LocalDate.now() ,
LocalDate.of( 2013 , Month.JANUARY , 21 )
)
java.time
The modern approach uses the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
Determine your dates.
LocalDate start = LocalDate.of( 2013 , Month.JANUARY , 3 ) ; // 3/1/2013
LocalDate stop = LocalDate.of( 2013 , Month.JANUARY , 21 ) ; // 21/01/2013
Today’s date
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ; // Or `ZoneId.systemDefault()` to indicate explicitly that you want the JVM’s current default time zone. Beware of that default changing *during* runtime.
LocalDate today = LocalDate.now( z ) ;
Elapsed days
The ChronoUnit enum calculates elapsed time in various granularity.
long daysElapsed = ChronoUnit.DAYS.between( start , stop ) ;
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, Java 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 Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
I searched this code on internet, but didn't manage to find. Though I'm replying late, this will be useful piece of code.
public static String getTimeLeft(String date) { // dateFormat = "yyyy-MM-dd"
String[] DateSplit = date.split("-");
int month = Integer.parseInt(DateSplit[1]) - 1, // if month is november then subtract by 1
year = Integer.parseInt(DateSplit[0]), day = Integer
.parseInt(DateSplit[2]), hour = 0, minute = 0, second = 0;
Calendar now = Calendar.getInstance();
int sec = second - Calendar.getInstance().get(Calendar.SECOND), min = minute
- Calendar.getInstance().get(Calendar.MINUTE), hr = hour
- Calendar.getInstance().get(Calendar.HOUR_OF_DAY), dy = day
- Calendar.getInstance().get(Calendar.DATE), mnth = month
- Calendar.getInstance().get(Calendar.MONTH), daysinmnth = 32 - dy;
Calendar end = Calendar.getInstance();
end.set(year, month, day);
if (mnth != 0) {
if (dy != 0) {
if (sec < 0) {
sec = (sec + 60) % 60;
min--;
}
if (min < 0) {
min = (min + 60) % 60;
hr--;
}
if (hr < 0) {
hr = (hr + 24) % 24;
dy--;
}
if (dy < 0) {
dy = (dy + daysinmnth) % daysinmnth;
mnth--;
}
if (mnth < 0) {
mnth = (mnth + 12) % 12;
}
}
}
String hrtext = (hr == 1) ? "hour" : "hours", dytext = (dy == 1) ? "day"
: "days", mnthtext = (mnth == 1) ? "month" : "months";
if (now.after(end)) {
return "";
} else {
String months = "", days = "", hours = "";
months = (mnth > 0) ? mnth + " " + mnthtext : "";
if (mnth <= 0) {
days = (dy > 0) ? dy + " " + dytext : "";
if (dy <= 0) {
hours = (hr > 0) ? hr + " " + hrtext : "";
}
}
//Log.d("DATE", months + " 1 " + days + " 2 " + hours);
return months + days + hours;
}
}
The other answers ignore time zone, which may be crucial depending on how accurate you want your countdown. If you do not specify a time zone, you get the JVM's default.
The java.util.Date & .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.
A bit of code in Joda-Time 2.3, untested (off the top of my head). Search StackOverflow for many more examples.
String input = "01/22/2013";
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy" ).withZone( timeZone );
DateTime future = formatterInput.parseDateTime( input );
DateTime now = new DateTime( timeZone );
int days = Days.daysBetween( now, future ).getDays();
Interval interval = new Interval( now, future );
Period period = new Period( interval );
Do some System.out.println calls for those variables and be amazed.
The string format you'll see is ISO 8601. You can create other formats as well.
I follow this question: Convert from java.util.date to JodaTime
I have date: Sun Jan 01 00:00:00 CET 1854
now I want to convert it to joda datetime:
DateTime dateTime = new DateTime(date);
and now when I print this date I got:
1853-12-31T23:57:44.000+00:57:44
what is wrong and why my date changed ? How I can get the same date ?
UPDATE:
I get date using calendar:
Calendar cal1 = Calendar.getInstance();
cal1.set(1854, 0, 1, 0, 0, 0);
cal1.getTime()
UPDATE2:
propably there is problem with milseconds:
Calendar cal1 = Calendar.getInstance();
cal1.set(1854, 0, 1, 0, 0, 0);
DateTime start = new DateTime(1854, 1, 1, 0, 0, 0);
System.out.println(start.getMillis());
System.out.println(cal1.getTime().getTime());
because this code return:
-3660598664000
-3660598799438
but I dont know why
UPDATE3:
Joda-Time uses the accurate time-zone database, which has Local Mean Time (LMT) for years before time-zones started. To quote Wikipedia:
Local mean time is a form of solar time that corrects the variations of local apparent time, forming a uniform time scale at a specific longitude.
The JDK doesn't use LMT, thus the times differ.
ok I solve it. Is isnt nice but it works what is important
Calendar calendar = Calendar.getInstance();
calendar.setTime(datum);
DateTime current = new DateTime(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1,
calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
IF you have the date as type of java.util.date you can use
java.util.Date date = ....
DateTime dateTime = new DateTime(date.getTime());
this code
Calendar cal1 = Calendar.getInstance();
cal1.set(1854, 0, 1, 0, 0, 0);
DateTime start = new DateTime(cal1.getTime());
System.out.println(start);
System.out.println(cal1.getTime());
outputs :
1854-01-01T00:00:00.941Z
Sun Jan 01 00:00:00 GMT 1854
I imagine the millisecond discrepancy is calendar choosign the saem time of day as now, to start the milliseconds count on. Whereas joda-time chooses midnight. Or something similarly obtuse. I try and stay away from java's built in Calendar and Date, they are an abomination.
The Answer by JodaStephen is correct and should be accepted.
The Joda-Time team have instructed us to migrate to the java.time framework built into Java 8 and later. So I was curious to try this problem in java.time and compare results.
The Question says the input data is for CET offset-from-UTC, but the code in the Question ignores that fact. My code below uses an offset of one hour ahead of UTC to account for CET.
java.time
The CET means one hour ahead of UTC. Since we have only an offset-from-UTC and not a full time zone, I use the OffsetDateTime class, for +01:00.
LocalDateTime localDateTime = LocalDateTime.of ( 1854 , 1 , 1 , 0 , 0 , 0 , 0 ); // The nineteenth century.
ZoneOffset offset = ZoneOffset.of ( "+01:00" ); // “CET” means one hour ahead of UTC.
OffsetDateTime odt = OffsetDateTime.of ( localDateTime , offset );
Instant instant = odt.toInstant (); // A moment on the timeline in UTC, with resolution in nanoseconds.
long m = instant.toEpochMilli ();
System.out.println ( "odt: " + odt + " | millis: " + m );
odt: 1854-01-01T00:00+01:00 | millis: -3660598800000
Joda-Time
Same code, but using Joda-Time 2.9.3.
DateTimeZone zone = DateTimeZone.forOffsetHoursMinutes ( 1 , 0 );
DateTime dateTime = new DateTime ( 1854 , 1 , 1 , 0 , 0 , zone );
long millis = dateTime.getMillis ();
System.out.println ( "dateTime: " + dateTime + " | millis: " + millis );
dateTime: 1854-01-01T00:00:00.000+01:00 | millis: -3660598800000
Result is same as java.time.
java.util.Calendar
For comparison only. Normally you should avoid the old java.util.Date/.Calendar classes as they have proven to be poorly designed, confusing, and troublesome.
Calendar calendar = Calendar.getInstance ();
calendar.set ( 1854 , 0 , 1 , 0 , 0 , 0 );
TimeZone zone = TimeZone.getTimeZone ( "GMT+01:00" );
calendar.setTimeZone ( zone );
long millis = calendar.getTimeInMillis ();
System.out.println ( "calendar: " + calendar + " | millis: " + millis );
calendar: java.util.GregorianCalendar[time=-3660598799715,areFieldsSet=true,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT+01:00",offset=3600000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=1854,MONTH=0,WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=1,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=285,ZONE_OFFSET=3600000,DST_OFFSET=0] | millis: -3660598799715
Different results. Here we have -3660598799715 versus -3660598800000 in java.time & Joda-Time, a difference of 285.
Europe/Brussels
I also tried all three with a time zone of Europe/Brussels rather than an offset-from-UTC.
In java.time. Using ZonedDateTime class rather than OffsetDateTime.
LocalDateTime localDateTime = LocalDateTime.of ( 1854 , 1 , 1 , 0 , 0 , 0 , 0 ); // The nineteenth century.
ZoneId zoneId = ZoneId.of ( "Europe/Brussels" );
ZonedDateTime zdt = ZonedDateTime.of ( localDateTime , zoneId );
Instant instant = zdt.toInstant (); // A moment on the timeline in UTC, with resolution in nanoseconds.
long m = instant.toEpochMilli ();
System.out.println ( "zdt: " + zdt + " | millis: " + m );
zdt: 1854-01-01T00:00+00:17:30[Europe/Brussels] | millis: -3660596250000
In Joda-Time. Only first line is different.
DateTimeZone zone = DateTimeZone.forID ( "Europe/Brussels" );
dateTime: 1854-01-01T00:00:00.000+00:17:30 | millis: -3660596250000
In java.util.Calendar. Some code except for the TimeZone line:
TimeZone zone = TimeZone.getTimeZone ( "Europe/Brussels" );
calendar: java.util.GregorianCalendar[time=-3660598799151,areFieldsSet=true,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Brussels",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=184,lastRule=java.util.SimpleTimeZone[id=Europe/Brussels,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=1854,MONTH=0,WEEK_OF_YEAR=1,WEEK_OF_MONTH=1,DAY_OF_MONTH=1,DAY_OF_YEAR=1,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=849,ZONE_OFFSET=3600000,DST_OFFSET=0] | millis: -3660598799151
All three using Europe/Brussels differ from their version with offset of +01:00.
And again java.time & Joda-Time agree with each other (-3660596250000), while differing from Calendar (-3660598799151), a difference of 2,549,151 (about 42 and a half minutes).
I have time data split in two strings - one string for date, and one for time.
I want to calculate the diff. of such two times in Java.
e.g.
time 1:"26/02/2011" and "11:00 AM"
time 2:"27/02/2011" and "12:15 AM"
Difference would be like 13 hours 15 minutes.
String str_date1 = "26/02/2011";
String str_time1 = "11:00 AM";
String str_date2 = "27/02/2011";
String str_time2 = "12:15 AM" ;
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
Date date1 = formatter.parse(str_date1 + " " + str_time1);
Date date2 = formatter.parse(str_date2 + " " + str_time2);
// Get msec from each, and subtract.
long diff = date2.getTime() - date1.getTime();
System.out.println("Difference In Days: " + (diff / (1000 * 60 * 60 * 24)));
Obs: This is only valid as an aproximation. See Losing Time on the Garden Path.)
try {
String date1 = "26/02/2011";
String time1 = "11:00 AM";
String date2 = "27/02/2011";
String time2 = "12:15 AM";
String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1 + " " + time1);
Date dateObj2 = sdf.parse(date2 + " " + time2);
System.out.println(dateObj1);
System.out.println(dateObj2);
long diff = dateObj2.getTime() - dateObj1.getTime();
double diffInHours = diff / ((double) 1000 * 60 * 60);
System.out.println(diffInHours);
System.out.println("Hours " + (int)diffInHours);
System.out.println("Minutes " + (diffInHours - (int)diffInHours)*60 );
} catch (ParseException e) {
e.printStackTrace();
}
output
Sat Feb 26 11:00:00 EST 2011
Sun Feb 27 00:15:00 EST 2011
13.25
Hours 13
Minutes 15.0
You need to first convert the strings to java.util.Date objects (using SimpleDateFormat.parse(String) for instance). Then you can use Date.getTime() for each of the two Date instances that you parsed and compute the difference in milliseconds or make use of a java.util.Calendar or the joda time API for advanced computations.
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();
Date myDate = new Date(difference);
The to show the Date :
String diff = df.format(myDate);
tl;dr
Duration.between(
ZonedDateTime.of(
LocalDate.parse( "26/02/2011" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ,
LocalTime.parse( "11:00 AM" , DateTimeFormatter.ofPattern( "hh:mm a" ) ) ,
ZoneId.of( "America/Montreal" )
)
,
ZonedDateTime.of(
LocalDate.parse( "27/02/2011" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ,
LocalTime.parse( "12:15 AM" , DateTimeFormatter.ofPattern( "hh:mm a" ) ) ,
ZoneId.of( "America/Montreal" )
)
).toString()
See live code in IdeOne.com.
Time zone
The Question and the other Answers all ignore the crucial issue of time zone. You cannot calculate elapsed time between two date-time strings without knowing the intended time zone. For example, in places with Daylight Saving Time (DST), on the night of the cut-over, a day may be 23 hours long or 25 hours long rather than 24 hours long.
java.time
The modern way to do date-time work is with the java.time classes. These supplant the troublesome old date-time classes such as java.util.Date and java.util.Calendar.
Local…
First parse the input strings. These lack any indication of time zone, so we parse them as Local… types.
Define a DateTimeFormatter to match your string inputs. By the way, in the future, use standard ISO 8601 formats when serializing date-time values to text.
DateTimeFormatter df = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "26/02/2011" , df ) ;
ld.toString(): 2011-02-2011
DateTimeFormatter tf = DateTimeFormatter.ofPattern( "hh:mm a" );
LocalTime lt = LocalTime.parse( "11:00 AM" , tf ) ;
lt.toString(): 11:00:00
ZoneId
You need to know the time zone intended by your business scenario. I will arbitrarily choose one.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime
Apply the zone to get a ZonedDateTime.
ZonedDateTime zdtStart = ZonedDateTime.of( ld , lt , z );
zdtStart.toString(): 2011-02-26T11:00:00-05:00[America/Montreal]
Duration
Do the same to get a zdtStop. Calculate the elapsed time as a span of time not attached to the timeline, in a Duration.
Duration d = Duration.between( zdtStart , zdtStop );
Call toString to generate a String in standard ISO 8601 format for durations: PnYnMnDTnHnMnS. The P marks the beginning while the T separates the two portions.
String output = d.toString();
d.toString(): PT13H15M
In Java 9 and later, call the to…Part methods to access each component.
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….
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.
try this one
you can calculate days,hours and minutes
public class TimeUtils {
public static final String HOURS = "hours";
public static final String MINUTES = "minutes";
public static final String DAYS = "days";
public static int findTheNumberBetween(String type, Date day1, Date day2) {
long diff = day2.getTime() - day1.getTime();
switch (type) {
case DAYS:
return (int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
case HOURS:
return (int) TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);
case MINUTES:
return (int) TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS);
}
return 0;
}
}
and the use it like
Date day1= TimeUtils.getDateTime("2016-12-08 02:06:14");
Date day2 = TimeUtils.getDateTime("2016-12-08 02:10:14");
Log.d(TAG, "The difference: "+TimeUtils.findTheNumberBetween(TimeUtils.MINUTES,day1,day2));