Decimal DateTime formatter in Java or Joda - java

I'm writing a file that requires dates to be in decimal format:
2007-04-24T13:18:09 becomes 39196.554270833331000
Does anyone have a time formatter that will do this (Decimal time is what VB/Office, etc. use)?
Basic code goes like follows:
final DateTime date = new DateTime(2007, 04, 24, 13, 18, 9, 0, DateTimeZone.UTC);
double decimalTime = (double) date.plusYears(70).plusDays(1).getMillis() / (Days.ONE.toStandardDuration().getMillis())); //=39196.554270833331000.
For the example above.
(I started on a DateTimePrinter that would do this, but it's too hard for now (I don't have the joda source linked, so I can't get ideas easily)).
Note: Decimal time is the number of days since 1900 - the . represents partial days. 2.6666666 would be 4pm on January 2, 1900

You can create a formatter that outputs the decimal fraction of the day. You need to use DateTimeFormatterBuilder to build up the pattern manually. The fraction is added using appendFractionOfDay().

Unfortunately your question is not very clear, but I have a hunch that with decimal time you mean a Julian date. There is a post about converting date to julian date in Java.

You can do this using the calendar class:
final long MILLIS_IN_DAY = 1000L * 60L * 60L * 24L;
final Calendar startOfTime = Calendar.getInstance();
startOfTime.setTimeZone(TimeZone.getTimeZone("UTC"));
startOfTime.clear();
startOfTime.set(1900, 0, 1, 0, 0, 0);
final Calendar myDate = Calendar.getInstance();
myDate.setTimeZone(TimeZone.getTimeZone("UTC"));
myDate.clear();
myDate.set(2007, 3, 24, 13, 18, 9); // 2007-04-24T13:18:09
final long diff = myDate.getTimeInMillis() - startOfTime.getTimeInMillis() + (2 * MILLIS_IN_DAY);
final double decimalTime = (double) diff / (double) MILLS_IN_DAY;
System.out.println(decimalTime); // 39196.55427083333
Something to note: This code will only work after 28th February 1900. Excel incorrectly counts 1900 as a leap year, which it of course is not. To circumvent the bug the calculation inserts an extra day (2 * MILLIS_IN_DAY), but this of course corrupts any date calculations before the imaginary leap year took place.

What's wrong with the getTime() method?

Related

Is the TimeUnit class broken?

I noticed a strange behaviour of the TimeUnit class, so I created this minimal example to reproduce it.
long differenceInDays;
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTimeInMillis(1466062306000l); // Thu Jun 16 2016 09:31:46 GMT+0200
c2.setTimeInMillis(1466028000000l); // Thu Jun 16 2016 00:00:00 GMT+0200
differenceInDays = TimeUnit.DAYS.convert(c2.getTimeInMillis() - c1.getTimeInMillis(), TimeUnit.MILLISECONDS);
System.out.println(differenceInDays); // obviously zero
c2.add(Calendar.DATE, +1);
differenceInDays = TimeUnit.DAYS.convert(c2.getTimeInMillis() - c1.getTimeInMillis(), TimeUnit.MILLISECONDS);
System.out.println(differenceInDays); // why zero and not one?
c2.add(Calendar.DATE, +1);
differenceInDays = TimeUnit.DAYS.convert(c2.getTimeInMillis() - c1.getTimeInMillis(), TimeUnit.MILLISECONDS);
System.out.println(differenceInDays); // suddenly a 1, but not a 2 like expected
It is obvious that the first time the difference is calculated it is 0, because not a whole day lies between the dates.
But the second time a whole day is added, so how can the difference be still 0?
Output:
001
I don't think this problem is daylight saving time or leap year related because I only do calculations within the same year, even month.
Here is a date to milliseconds calculator for you to check.
You can see better what's going on here with simple math:
c1 = 1466062306000
c2 = 1466028000000
d = 86400000 // one day
c2 - c1 = -34306000 // negative, but less than one day in magnitude
c2 - c1 + d = 52094000 // less than one day
c2 - c1 + d + d = 138494000 // more than one day, less than two days
The correct way to handle this, assuming you're using Java 8, is as follows:
// Decide what time zone you want to work in
ZoneId tz = ZoneId.of("Europe/Berlin");
// If you wanted the local time zone of the system,
// Use this instead:
// ZoneId tz = ZoneId.systemDefault();
// Get instants from the timestamps
Instant i1 = Instant.ofEpochMilli(1466062306000l);
Instant i2 = Instant.ofEpochMilli(1466028000000l);
// Get the calendar date in the specified time zone for each value
LocalDate d1 = i1.atZone(tz).toLocalDate();
LocalDate d2 = i2.atZone(tz).toLocalDate();
// Get the difference in days
long daysBetween = ChronoUnit.DAYS.between(d2, d1);
If your inputs are truly Calendar objects instead of timestamps, I'd suggest Calendar.toInstant() as described in the Legacy Date-Time Code guidance.
If you're using Java 7 or earlier, you will find similar capabilities from the Joda Time library.
if you really don't want to use any of these, and still do things the old (hard) way, then see this example.

Java JTextField with date and time format [duplicate]

I have the estimated time the it would take for a particular task in minutes in a float. How can I put this in a JFormattedTextField in the format of HH:mm:ss?
For a float < 1440 you can get around with Calendar and DateFormat.
float minutes = 100.5f; // 1:40:30
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.add(Calendar.MINUTE, (int) minutes);
c.add(Calendar.SECOND, (int) ((minutes % (int) minutes) * 60));
final Date date = c.getTime();
Format timeFormat = new SimpleDateFormat("HH:mm:ss");
JFormattedTextField input = new JFormattedTextField(timeFormat);
input.setValue(date);
But be warned that if your float is greater than or equal to 1440 (24 hours) the Calendar method will just forward a day and you will not get the expected results.
JFormattedTextField accepts a Format object - you could thus pass a DateFormat that you get by calling DateFormat#getTimeInstance(). You might also use a SimpleDateFormat with HH:mm:ss as the format string.
See also:
http://download.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html#format
If you're not restricted to using a JFormattedTextField, you might also consider doing your own formatting using the TimeUnit class, available since Java 1.5, as shown in this answer: How to convert Milliseconds to "X mins, x seconds" in Java?

Java, get days between two dates

In java, I want to get the number of days between two dates, excluding those two dates.
For example:
If first date = 11 November 2011 and the second date = 13 November 2011
then it should be 1.
This is the code I am using but doesn't work (secondDate and firstDate are Calendar objects):
long diff=secondDate.getTimeInMillis()-firstDate.getTimeInMillis();
float day_count=(float)diff / (24 * 60 * 60 * 1000);
daysCount.setText((int)day_count+"");
I even tried rounding the results but that didn't help.
How do I get the number of days between dates in java excluding the days themselves?
I've just tested on SDK 8 (Android 2.2) the following code snippet:
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
date1.clear();
date1.set(
datePicker1.getYear(),
datePicker1.getMonth(),
datePicker1.getDayOfMonth());
date2.clear();
date2.set(
datePicker2.getYear(),
datePicker2.getMonth(),
datePicker2.getDayOfMonth());
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
float dayCount = (float) diff / (24 * 60 * 60 * 1000);
textView.setText(Long.toString(diff) + " " + (int) dayCount);
it works perfectly and in both cases (Nov 10,2011 - Nov 8,2011) and (Nov 13,2011 - Nov 11,2011) gives dayCount = 2.0
Get Days between java.util.Dates, ignoring daylight savings time
Quick and dirty hack:
public int get_days_between_dates(Date date1, Date date2)
{
//if date2 is more in the future than date1 then the result will be negative
//if date1 is more in the future than date2 then the result will be positive.
return (int)((date2.getTime() - date1.getTime()) / (1000*60*60*24l));
}
This function will work 99.99% of the time, except when it surprises you later on in the edge cases during leap-seconds, daylight savings, timezone changes leap years and the like. If you are OK with the calculation being off by 1 (or 2) hours once in a while, this will suffice.
Get Days between Dates taking into account leapseconds, daylight savings, timezones, etc
If you are asking this question you need to slap yourself. What does it mean for two dates to be at least 1 day apart? It's very confusing. What if one Date is midnight in one timezone, and the other date is 1AM in another timezone? Depending on how you interpret it, the answer is both 1 and 0.
You think you can just force the dates you pass into the above function as Universal time format; that will fix some of your problems. But then you just relocate the problem into how you convert your local time to a universal time. The logical conversion from your timezone to universal time may not be what is intuitive. In some cases you will get a day difference when the dates passed in are obviously two days apart.
And you think you can deal with that? There are some simplistic calendar systems in the world which are constantly changing depending on the harvest season and installed political rulers. If you want to convert their time to UTC, java.util.Date is going to fail you at the worst moment.
If you need to calculate the days between dates and it is critical that everything come out right, you need to get an external library called Joda Time: (They have taken care of all the details for you, so you can stay blissfully unaware of them): http://joda-time.sourceforge.net/index.html
java.time
The java.time API, released with Java-8 in March 2014, supplanted the error-prone legacy date-time API. Since then, using this modern date-time API has been strongly recommended.
Solution using modern date-time API
Using Calendar#toInstant, convert your java.util.Calendar instances into java.time.Instant and then into java.time.ZonedDateTime instances and then use ChronoUnit.DAYS.between to get the number of days between them.
Demo:
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
// Sample start and end dates as java.util.Date
Calendar startCal = Calendar.getInstance();
startCal.set(2011, 10, 11); // 11 November 2011
Calendar endCal = Calendar.getInstance();
endCal.set(2011, 10, 13); // 13 November 2011
// Convert the java.util.Calendar into java.time.ZonedDateTime
// Replace ZoneId.systemDefault() with the applicable ZoneId
ZonedDateTime startDateTime = startCal.toInstant().atZone(ZoneId.systemDefault());
ZonedDateTime endDateTime = endCal.toInstant().atZone(ZoneId.systemDefault());
// The end date is excluded by default. Subtract 1 to exclude the start date
long days = ChronoUnit.DAYS.between(startDateTime, endDateTime) - 1;
System.out.println(days);
}
}
Output:
1
Learn more about the modern Date-Time API from Trail: Date Time.
Don't use floats for integer calculations.
Are you sure your dates are days? The precision of the Date type is milliseconds. So the first thing you need to do is round the date to something which doesn't have hours. Example: It's just one hour from 23:30 2011-11-01 to 00:30 2011-11-02 but the two dates are on different days.
If you are only going to be dealing with dates between the years 1900 and 2100, there is a simple calculation which will give you the number of days since 1900:
public static int daysSince1900(Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
int year = c.get(Calendar.YEAR);
if (year < 1900 || year > 2099) {
throw new IllegalArgumentException("daysSince1900 - Date must be between 1900 and 2099");
}
year -= 1900;
int month = c.get(Calendar.MONTH) + 1;
int days = c.get(Calendar.DAY_OF_MONTH);
if (month < 3) {
month += 12;
year--;
}
int yearDays = (int) (year * 365.25);
int monthDays = (int) ((month + 1) * 30.61);
return (yearDays + monthDays + days - 63);
}
Thus, to get the difference in days between two dates, you calculate their days since 1900 and calc the difference. Our daysBetween method looks like this:
public static Integer getDaysBetween(Date date1, Date date2) {
if (date1 == null || date2 == null) {
return null;
}
int days1 = daysSince1900(date1);
int days2 = daysSince1900(date2);
if (days1 < days2) {
return days2 - days1;
} else {
return days1 - days2;
}
}
In your case you would need to subtract an extra day (if the days are not equal).
And don't ask me where this calculation came from because we've used it since the early '90s.
I have two suggestions:
Make sure your float day_count is calculated correctly
float day_count = ((float)diff) / (24f * 60f * 60f * 1000f);
If it's rounding error, try using floor method
daysCount.setText("" + (int)Math.floor(day_count));

JTextField time in HH:mm:ss

I have the estimated time the it would take for a particular task in minutes in a float. How can I put this in a JFormattedTextField in the format of HH:mm:ss?
For a float < 1440 you can get around with Calendar and DateFormat.
float minutes = 100.5f; // 1:40:30
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.add(Calendar.MINUTE, (int) minutes);
c.add(Calendar.SECOND, (int) ((minutes % (int) minutes) * 60));
final Date date = c.getTime();
Format timeFormat = new SimpleDateFormat("HH:mm:ss");
JFormattedTextField input = new JFormattedTextField(timeFormat);
input.setValue(date);
But be warned that if your float is greater than or equal to 1440 (24 hours) the Calendar method will just forward a day and you will not get the expected results.
JFormattedTextField accepts a Format object - you could thus pass a DateFormat that you get by calling DateFormat#getTimeInstance(). You might also use a SimpleDateFormat with HH:mm:ss as the format string.
See also:
http://download.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html#format
If you're not restricted to using a JFormattedTextField, you might also consider doing your own formatting using the TimeUnit class, available since Java 1.5, as shown in this answer: How to convert Milliseconds to "X mins, x seconds" in Java?

How to get Exact day difference between two dates in java or groovy?

I am calculating the difference between two sql dates, TripStartDate and TripEndDate.
If TripStartDate= 2011-03-04 09:35:00 and TripEndDate = 2011-03-04 10:35:00 then I should get the number of day is 1 (because trip happened on that day).
Like this:
If TripStartDate = 2011-03-04 09:35:00 and TripEndDate = 2011-03-05 09:35:00 then method should return 2 days (because trip happened on both days).
If TripStartDate = 2011-03-04 09:35:00 and TripEndDate = 2011-04-04 09:35:00 then method should return 32 days. (because 28 days in march and 4 days in April).
Calculation should be based on only dates and month of year (not taking time in consideration). Please help me . Thanks in advance...
In Java I guess you would drop the time and calculate the day difference
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.set(2011, 03, 04);
cal2.set(2011, 04, 04);
long milis1 = cal1.getTimeInMillis();
long milis2 = cal2.getTimeInMillis();
long diff = milis2 - milis1;
long days = diff / (24 * 60 * 60 * 1000);
EDIT Quite surprisingly for me, that ^ code really doesn't work always... apparently there are some 'leap seconds' that mess up the maths. There are quite enough links already proposed to you in comments. I would go with joda time library.
FYI, in Groovy this would be something along the lines of:
fourthMarch = Date.parse( 'yyyy-MM-dd', '2011-03-04' )
fifthMarch = Date.parse( 'yyyy-MM-dd', '2011-03-05' )
fourthApril = Date.parse( 'yyyy-MM-dd', '2011-04-04' )
assert 2 == fifthMarch - fourthMarch + 1
assert 32 == fourthApril - fourthMarch + 1
We need to add 1 as the dates are inclusive
Here's the usual way to do this, in Java 8.
LocalDate start = LocalDate.of(2011, 3, 4); // Or whatever - this is Y, M, D
LocalDate end = LocalDate.of(2011, 4, 4);
return ChronoUnit.DAYS.between(start, end) + 1;
// The +1 is for the inclusive reckoning

Categories