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
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();
This question already has answers here:
How to subtract n days from current date in java? [duplicate]
(5 answers)
Closed 9 years ago.
In my shopping cart application, I am storing all the purchase dates in timestamp.
Suppose, I want to get the timestamp of purchase date n days before (n is configurable). How will I get it using java?
example: something like
purchasedateBefore5days = currentTimestamp_in_days - 5;
I am getting current timestamp using
long currentTimestamp = Math.round(System.currentTimeMillis() / 1000);
How can i subtract n days from it. I am a beginner. Please help on this.
Use the Calendar class:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -5);
long fiveDaysAgo = cal.getTimeInMillis();
You can use the Calendar class in Java , use its set() method to add/subtract the required number of days from the Calendar.DATE field.
To subtract n days from today , Use c.get(Calendar.DATE)-n. Sample code :
Calendar c = Calendar.getInstance();
System.out.println(c.getTime()); // Tue Jun 18 17:07:45 IST 2013
c.set(Calendar.DATE, c.get(Calendar.DATE)-5);
System.out.println(c.getTime()); // Thu Jun 13 17:07:45 IST 2013
Date d = initDate();//intialize your date to any date
Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 ); //Subtract n days
Also possible duplicate .
That currentTimestamp must be passed to a Calendar instance.
from Calendar you can subtract X days.
Get the milliseconds from calendar and is done.
You can play aorund with the following code snippet, to form it the way you want:
Calendar c = Calendar.getInstance();
c.setTimeInMillis(milliSeconds);
c.add(Calendar.DATE, -5);
Date date = c.getTime();
Calendar calendar=Calendar.getInstance();
calendar.add(Calendar.DATE, -5);
using Java.util.Calendar Class
Calendar.DATE
This is the field number for get and set indicating the day of the month. , to subtract 5 days from the current time of the calendar, you can achieve it by calling.
Try this..
long timeInMillis = System.currentTimeMillis();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeInMillis);
cal.set(Calendar.DATE, cal.get(Calendar.DATE)-5);
java.util.Date date1 = cal.getTime();
System.out.println(date1);
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?
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
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?