Get difference between two Joda dates in seconds - java

I am trying to use joda API in my app for playing with Date object.
In some activity i am storing joda datetime in sharedpreference using following code
prefsEdit.putLong(context.getString(R.string.last_status_change_time_key) , DateTime.now().getMillis());
Now in some other activity, i m fetching this stored preference and calculating the difference between dates using following code
long lastStatusChangeTime = objSharedPref.GetAppLongPrefByKey(R.string.last_status_change_time_key);
DateTime now = DateTime.now();
DateTime dateTime = new DateTime(lastStatusChangeTime);
Seconds seconds = Seconds.secondsBetween(now, dateTime);
int n = seconds.getSeconds();
The code always return me values in minus eg -31 , -12 etc..
It is not calculating the difference correctly .
What is missing ??

The declaration of secondsBetween() is:
secondsBetween(ReadableInstant start, ReadableInstant end)
In order to have positive result the start date should be a date before the end date.
It is because secondsBetween() doesn't return an absolute value.
In your example dateTime is obviously before now, so in order to get positive values the invocation should be:
Seconds seconds = Seconds.secondsBetween(dateTime, now);
instead of:
Seconds seconds = Seconds.secondsBetween(now, dateTime); // <- wrong order as `startDate` parameter is a date after `endDate` parameter
and your code could be:
long lastStatusChangeTime = objSharedPref.GetAppLongPrefByKey(R.string.last_status_change_time_key);
DateTime now = DateTime.now();
DateTime dateTime = new DateTime(lastStatusChangeTime);
Seconds seconds = Seconds.secondsBetween(dateTime, now); // <-- Here is the difference
int n = seconds.getSeconds();

Just use native Java code.
long oldTime = Calendar.getInstance().getTime().getTime();
Thread.sleep(10*1000);
long newTime = Calendar.getInstance().getTime().getTime();
long diffInMillisecods = newTime - oldTime;
long diffInSeconds = diffInMillisecods / 1000;

Related

How to calculate remaining days?

private long calculateRemainingDays() {
final Calendar c = Calendar.getInstance();
c.set(2015, 7, 23);
final Calendar today = Calendar.getInstance();
final long millis = c.getTimeInMillis()
- today.getTimeInMillis();
// Convert to days
final long days = millis / 86400000;
return days;
}
I need to add a function in my android application. I want a remaining days from current day to 2015/9/30. When the date is change to next day, the remaining days will decrease. I would like to say like that:
7 days remaining... 6/5/4/etc... Please help me to get correct remaining days. Sorry for my poor english. Thanks!
Use Calender.JULY instead of 7 in the parameters for the set() method.
7 = August.
6 = July.
As it starts with January as 0. It's better to use the static instance variables like Calender.JANUARY.
But as you want to calculate till 2015/9/30, you should set the value as
c.set(2015, Calender.SEPTEMBER, 09);
The rest of the code seems ok. It will return the correct number of days.
Try this :-
final long millis = c.getTimeInMillis()
- today.getTimeInMillis();
System.out.println ("Days: " + TimeUnit.DAYS.convert(millis , TimeUnit.MILLISECONDS));
if you don't mind using joda.time
you can do something of this form:
final Calendar c = Calendar.getInstance();
c.set(2015, Calender.SEPTEMBER, 30);
Date endDate = c.getTime();
Instant startInstant = new Instant(new Date());
Instant endInstant = new Instant(endDate);
Days days = Days.daysBetween(startInstant, endInstant);

Is it possible to get timestamp format 'dd-MM-yyyy HH:mm:ss.SSS.xxxxxx.nnnnnnnnn' in java? [duplicate]

This is my code:
long currentTime = System.currentTimeMillis();
Date date = new Date(currentTime); // if you really have long
String result = new SimpleDateFormat("HH:mm:ss").format(date.getTime());
Is it possible to add milliseconds and nanoseconds to the date format ?
You can add milliseconds by adding SSS at the end, such as the format will be HH:mm:ss.SSS.
There is no reference in the SimpleDateFormat to nanoseconds. Usually System.nanoTime() is used for performance debugging and not for display purposes.
String result = new SimpleDateFormat("HH:mm:ss:SSS").format(date);
"HH:mm:ss:SSS" //SSS stands for milliseconds
Check SimpleDateFormat API for more info
String timeStamp = new SimpleDateFormat("dd:MM:yyyy_HH:mm:ss:SSS").format(Calendar.getInstance().getTime());
timeStamp = timeStamp + ":" + System.nanoTime();
This gave me output,
24:03:2014_18:24:09:890:2018826751601473

How to round off timestamp in milliseconds to nearest seconds?

How to round off the current timestamp in milliseconds to seconds?
If this is the current timestamp in milliseconds I have -
1384393612958
The if I am rounding off to nearest second then will it be like this?
Time in MS rounded off to nearest Second = 1384393612000
I might need to do this both in Java and C++.
If you are using Python:
old_number = 1384393612958
new_number = 1000 * (old_number / 1000)
print new_number
Basically you want to use an integer number, divide by one thousand (to shave off the milli-seconds), and then multiple by thousand to get the ms value rounded to seconds.
In Java you can use Calendar to something like this:
Calendar cal = Calendar.getInstance().setTimeInMillis(millisec);
int seconds = cal.get(Calendar.SECONDS);
Alternatively (and can work for C++ too) you can do:
int sec = ((millisec + 500) / 1000);
adding 500 ms allows you to round the number properly.
tl;dr
Instant.ofEpochMilli( 1_384_393_612_958L )
.truncatedTo( ChronoUnit.SECONDS )
.toEpochMilli()
java.time
The modern approach in Java uses the java.time classes.
The Instant class represents a point on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.ofEpochMilli( 1_384_393_612_958L ) ;
Instant instantTrunc = instant.truncatedTo( ChronoUnit.SECONDS ) ;
long millis = instantTrunc.toEpochMilli() ;
This is needed to convert java date object to mysql datetime formatted string in sql queries.
Conversion:
Calendar cal = Calendar.getInstance();
cal.setTime(this.id.getCreatedOn());
if (cal.get(Calendar.MILLISECOND) >= 500 ) {
System.out.println("Round off milliseconds to seconds");
cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + 1);
}
Date roundedCreatedOn = cal.getTime();
Actual query string contains:
createdOn = '" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(roundedCreatedOn)+ "'"
In javascript, using the moment.js library:
moment(timestamp).startOf('second')

Milliseconds and nanoseconds in time format

This is my code:
long currentTime = System.currentTimeMillis();
Date date = new Date(currentTime); // if you really have long
String result = new SimpleDateFormat("HH:mm:ss").format(date.getTime());
Is it possible to add milliseconds and nanoseconds to the date format ?
You can add milliseconds by adding SSS at the end, such as the format will be HH:mm:ss.SSS.
There is no reference in the SimpleDateFormat to nanoseconds. Usually System.nanoTime() is used for performance debugging and not for display purposes.
String result = new SimpleDateFormat("HH:mm:ss:SSS").format(date);
"HH:mm:ss:SSS" //SSS stands for milliseconds
Check SimpleDateFormat API for more info
String timeStamp = new SimpleDateFormat("dd:MM:yyyy_HH:mm:ss:SSS").format(Calendar.getInstance().getTime());
timeStamp = timeStamp + ":" + System.nanoTime();
This gave me output,
24:03:2014_18:24:09:890:2018826751601473

What is the equivalent of getTime(), which is a method in Date, in joda.time.LocalDate?

I was doing a simple calculation to get the difference between two dates. If I was using a Date class I can do like this:
Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
But I couldn't find a method like getTime() in Local date. Is there any way so I can easily get what I am trying to achieve?
I even tried to change my LocalDate object to a temporary date object like this:
LocalDate date=new LocalDate();
Date d=date.toDate();
but the method toDate() isnt working . i.e it says it is not recognized method.(so compile time error) but from what I can see it is in the Documentation
Thank you for your time and of course happy Thanksgiving.
Days.daysBetween() is the answer.
LocalDate now = new LocalDate();
LocalDate past = now.minusDays(300);
int days = Days.daysBetween(past,now).getDays();
Never convert a LocalDate to a Java Date (two completey different beasts) if you are just dealing with dates. A Jodatime Localdate is a true "Calendar date", i.e. , a tuple of {day,month,year} (together with a Gregorian calendar specification), and has nothing to do with "physical time", with seconds, hours, etc. If you need to do dates arithmetic, stick with Localdate and you'll never need to worry about stupid bugs (timezones, DST, etc) which could arise if you dates arithmetic using java Dates.
Try something like this:
LocalDate date = new LocalDate();
Date utilDate = date.toDateTimeAtStartOfDay( timeZone ).toDate( );
or refer to this post
How to convert Joda LocalDate to java.util.Date?
I tested this sample code to find out the difference in days, you can find the difference as per your needs.
Please see http://joda-time.sourceforge.net/key_period.html
LocalDate currentDate = new LocalDate();
LocalDate previousDate = currentDate.minusDays(1);
System.out.println(currentDate);
System.out.println(previousDate);
Period periodDifference = new Period(currentDate, previousDate, PeriodType.days());
System.out.println(periodDifference);
private long diff(Calendar c1, Calendar c2) {
long d1 = c1.getTimeInMillis();
long d2 = c2.getTimeInMillis();
return ((d2 - d1) / (60*60*24*1000));
}
Have not found any equivalents for LocalDate as they are not exact.
But there are several equivalents for LocalDateTime:
LocalDateTime localDateTime = LocalDateTime.now();
long longValue = ZonedDateTime.of(localDateTime, ZoneId.systemDefault()).toInstant().toEpochMilli();
or
long longValue = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
or
long longValue = localDateTime.toInstant(OffsetDateTime.now().getOffset()).toEpochMilli();
or
long longValue = Timestamp.valueOf(localDateTime).getTime();

Categories