Java JTextField with date and time format [duplicate] - java

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?

Related

Fastest way to get hour of java.util.date?

When starting from ajava.util.date object: what is the best way getting the hour part as an integer regarding performance?
I have to iterate a few million dates, thus performance matters.
Normally I'd get the hour as follows, but maybe there are better ways?
java.util.Date date;
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
In UTC:
int hour = (int)(date.getTime() % 86400000) / 3600000;
or
long hour = (date.getTime() % 86400000) / 3600000;
Date dateInput = new Date();
since calendar starts at 01.01.1970, 01:00. you have to make further modifications
to the code.using below approach avoids that so this will performs faster.
dateInput.toInstant().atZone(ZoneId.systemDefault()).getHour();

Compare same date using java

The date is selected by the user using a drop down for year, month and day. I have to compare the user entered date with today's date. Basically see if they are the same date. For example
the user entered 02/16/2012. And if today is 02/16/2012 then I have to display a message. How do I do it?
I tried using milliseconds but that gives out wrong results.
And what kind of object are you getting back? String, Calendar, Date? You can get that string and compare it, at least that you think you'll have problems with order YYYY MM DD /// DD MM YYY in that case I suggest to create a custom string based on your spec YYYYMMDD and then compare them.
Date d1 = new Date();
Date d2 = new Date();
String day1 = d1.getYear()+"/"+d1.getMonth()+"/"+d1.getDate();
String day2 = d2.getYear()+"/"+d2.getMonth()+"/"+d2.getDate();
if(day1.equals(day2)){
System.out.println("Same day");
}
Dates in java are moments in time, with a resolution of "to the millisecond". To compare two dates effectively, you need to first set both dates to the "same time" in hours, minutes, seconds, and milliseconds. All of the "setTime" methods in a java.util.Date are depricated, because they don't function correctly for the internationalization and localization concerns.
To "fix" this, a new class was introduced GregorianCalendar
GregorianCalendar cal1 = new GregorianCalendar(2012, 11, 17);
GregorianCalendar cal2 = new GregorianCalendar(2012, 11, 17);
return cal1.equals(cal2); // will return true
The reason that GregorianCalendar works is related to the hours, minutes, seconds, and milliseconds being initialized to zero in the year, month, day constructor. You can attempt to approximate such with java.util.Date by using deprecated methods like setHours(0); however, eventually this will fail due to a lack of setMillis(0). This means that to use the Date format, you need to grab the milliseconds and perform some integer math to set the milliseconds to zero.
date1.setHours(0);
date1.setMinutes(0);
date1.setSeconds(0);
date1.setTime((date1.getTime() / 1000L) * 1000L);
date2.setHours(0);
date2.setMinutes(0);
date2.setSeconds(0);
date2.setTime((date2.getTime() / 1000L) * 1000L);
return date1.equals(date2); // now should do a calendar date only match
Trust me, just use the Calendar / GregorianCalendar class, it's the way forward (until Java adopts something more sophisticated, like joda time.
There is two way you can do it. first one is format both the date in same date format or handle date in string format.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date1 = sdf.format(selectedDate);
String date2 = sdf.format(compareDate);
if(date1.equals(date2)){
}else{
}
Or
Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-date->);
if(!toDate.before(nowDate))
//display your report
else
// don't display the report
Above answers are correct but consider using JodaTime - its much simpler and intuitive API.
You could set DateTime using with* methods and compare them.
Look at this answer

Time and Calendar

How do I add/subtract two time objects. I have two time objects (arrival and departure) in format of "yyyy/MMM/dd HH:mm:ss". I need to print the difference between departure and arrival time. I am generating time ad below:
public String getTime() {
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
return formatter.format(currentDate.getTime());
}
Can I get time in mills and than format it when I needed to print ?
Take a look at Joda Time library.
You can easily subtract and add DateTime and find out interval easily :
// interval from start to end
DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0);
DateTime end = new DateTime(2005, 1, 1, 0, 0, 0, 0);
Interval interval = new Interval(start, end);
something like this.....
public long getTimeDiff() throws Exception {
String arrival = "2011/Nov/10 13:15:24";
String departure = "2011/Jan/10 13:15:24";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss");
java.util.Date date1 = formatter.parse(arrival);
java.util.Date date2 = formatter.parse(departure);
return date2.getTime() - date1.getTime();
}
Convert them to date and then to long and subtract, that would give the time difference in milli seconds,
Date d1 = DateFormat.parse(time1);
Date d2 = DateFormat.parse(time2);
long diffInMilliSeconds = d1.getTime()-d2.getTime();
You can get time in milliseconds for both calendars using getTime method. When you can convert the result of subtraction to measure units that you need. If you're going to work with time/duration seriously when take a look at Joda library
Upd. You should call getTime twice. First object being returned is Date, when you call getTime on Date you get long value.
I would convert the two time/Date objects in milliseconds. Then i would subtract them (we are dealing with longs).
Then i would create a Date object from the resulting long value. After that you can construct a Calendar with Calendar.setDate(Date).
Regards!
Yes, start with your Dates and use getTime() to convert to milliseconds (or getTimeInMillis() for your Calendars). That give you long values you can subtract. That's the easy part.
Then you can convert these milliseconds into a readable format yourself. But it probably makes sense to use a packaged library to do it.
Some folks like the Joda library for these types of date calculations. I find Commons Lang is fantastic. It provides DateUtils which is useful if you find you want to perform calculations like rounding or truncating your dates to the nearest minute or hour etc. The part that will be most useful to you is the DurationFormatUtils class which gives you functions like formatDurationHMS to format into nice Hour:Minute:Second display and formatDurationWords to get text (fancy!) or other similar functions to easily format your milliseconds into a nicely human-readable format.

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?

Decimal DateTime formatter in Java or Joda

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?

Categories