Eclipse is warning that I'm using a deprecated method:
eventDay = event.getEvent_s_date().getDate();
So I rewrote it as
eventDay = DateUtil.toCalendar(event.getEvent_s_date()).get(Calendar.DATE);
It seems to work but it looks ugly. My question is did I refactor this the best way? If not, how would you refactor? I need the day number of a date stored in a bean.
I ended up adding a method in my DateUtils to clean it up
eventDay = DateUtil.getIntDate(event.getEvent_s_date());
public static int getIntDate(Date date) {
return DateUtil.toCalendar(date).get(Calendar.DATE);
}
It's fine. To me the uglier bit is the underscore in the method name. Java conventions frown upon underscores there.
You may want to take a look at joda-time. It is the de-facto standard for working with date/time:
new DateTime(date).getDayOfMonth();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Integer date = cal.get(Calendar.DATE);
/*Similarly you can get whatever value you want by passing value in cal.get()
ex DAY_OF_MONTH
DAY_OF_WEEK
HOUR_OF_DAY
etc etc..
*/
You can see java.util.Calendar API.
With Java 8 and later, it is pretty easy. There is LocalDate class, which has getDayOfMonth() method:
LocalDate date = now();
int dayOfMonth = date.getDayOfMonth();
With the java.time classes you do not need those third party libraries anymore. I would recommend reading about LocalDate and LocalDateTime.
If you want a more elegant Date/Time api, use Joda Time.
Related
Hi I want to iterate through a date range without using any libraries. I want to start on 18/01/2005(want to format it to yyyy/M/d) and iterate in day intervals until the current date. I have formatted the start date, but I dont know how I can add it to a calendar object and iterate. I was wondering if anyone can help. Thanks
String newstr = "2005/01/18";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/M/d");
Date date = format1.parse(newstr);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
while (someCondition(calendar)) {
doSomethingWithTheCalendar(calendar);
calendar.add(Calendar.DATE, 1);
}
Use SimpleDateFormat to parse a string into a Date object or format a Date object into a string.
Use class Calendar for date arithmetic. It has an add method to advance the calendar, for example with a day.
See the API documentation of the classes mentioned above.
Alternatively, use the Joda Time library, which makes these things easier. (The Date and Calendar classes in the standard Java API have a number of design issues and are not as powerful as Joda Time).
I have to use java.util.Calendar in GWT entry point, but I got error while running the application, that is because GWT is not able to find source code, is there anyway I could fix this issue.
Thanks in advance!!!
java.util.Calendar is not an emulated class. You can find a list of emulated classes here:
http://code.google.com/webtoolkit/doc/latest/RefJreEmulation.html
I would strongly advise not to use any date/calendar library on the client side. You will probably only get yourself into trouble. In fact, even though java.sql.Date and java.util.Date are emulated in GWT, I would not use these either. If you're looking to use Calendar, then chances are you want to support timezones on the client. Using the emulated Date classes, you will somehow have to convert the client's Date from the browser's timezone to some target timezone (GMT or whatever the user defined in user preferences?). This will most definitely be error prone. Using GWT's TimeZone adds other issues. For instance, how do you map between java TimeZones and GWT TimeZones?
I recommend doing all date manipulation AND formatting on the server. On the client, you can simply use a date/month/year triplet. The server can have an association between user (or organization) and java.util.TimeZone (or joda timezone). Using the triplet and timezone you can easily create the specific instance in time.
You may be able to use com.google.gwt.user.datepicker.client.CalendarUtil.
No there is no way to use the java.util.Calendar in GWT because there is no equivalent in JavaScript. But there is an accepted feature request for it. Maybe you will find some hints in the comments of the request.
The following shows how to use Joda Time to extract any date information from a Java Date type with Joda Times format() function and use it to build a new Date() using Joda Time's parse() function.
static DateTimeFormat dtf = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss.SSS");
static DateTimeFormat datefmt = DateTimeFormat.getFormat("yyyy-MM-dd ");
static DateTimeFormat timefmt = DateTimeFormat.getFormat("HH:mm:ss.SSS");
public Date getDateTime(Date date, Date time) {
String datetime = datefmt.format(date) + timefmt.format(time);
return dtf.parse(datetime);
}
Have you tried adding actual code of the class to your project? Some Java SDK classes compile well even though they are not in JRE white list.
For those who prefer implementing the math directly, here is a solution for how to add days to an existing date object without using Calendar or any deprecated functions:
private Date addDays(Date dateIn, int numDays)
{
long milisPerDay = 86400000;
// convert the dateIn to milliseconds
long dateInMilis = dateIn.getTime();
// add numDays to the date
dateInMilis = dateInMilis + (numDays * milisPerDay);
return new Date(dateInMilis);
}
Here's how to get the current year as a String (very useful for Copyright notices)
long time = System.currentTimeMillis();
long milisPerYear = new BigInteger("31536000000").longValue();
String currentYear = String.valueOf((int) Math.floor(time / milisPerYear) + 1970);
Finding the constants such as number of miliseconds in a day, year, etc. is easy with Google. The tricky part is adding months, since the number of milliseconds in a month is going to depend on the month. If there's any demand for it, I'd be happy to write a function and post it here in order to add and subtract months.
What's the most efficient way to remove the time portion from a Java date object using only Classes from within the JDK?
I have the following
myObject.getDate() =
{java.util.Date}"Wed May 26 23:59:00
BST 2010"
To reset the time back to 00:00:00, I'm doing the following
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date myDate = sdf.parse(sdf.format(myObject.getDate()));
The output is now
myDate = {java.util.Date}"Wed May 26
00:00:00 BST 2010"
Is there a better way to achieve the same result?
More verbose, but probably more efficient:
Calendar cal = GregorianCalendar.getInstance();
cal.setTime(date);
// cal.set(Calendar.HOUR, 0); // As jarnbjo pointed out this isn't enough
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Also, you don't need to worry about locale settings, which may cause problems with string to date conversions.
If you have Apache commons, you can use DateUtils.truncate():
Date myDate = DateUtils.truncate(myObject.getDate(), Calendar.DATE)
(If you don't have access to Apache Commons, DateUtils.truncate() is implemented basically the same as kgiannakakis's answer.)
Now, if you want "clever" code that is very fast, and you don't mind using deprecated functions from java.util.Date, here is another solution. (Disclaimer: I wouldn't use this code myself. But I have tested it and it works, even on days when DST starts/ends.)
long ts = myObject.getDate().getTime() - myObject.getDate().getTimezoneOffset()*60000L;
Date myDate = new Date(ts - ts % (3600000L*24L));
myDate.setTime(myDate.getTime() + myDate.getTimezoneOffset()*60000L);
These methods are deprecated, but given a Date, you can do something like this:
Date d = ...;
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
You should use a Calendar if possible. You'd then use the cal.set(Calendar.MINUTE, 0), etc.
It should be mentioned that if it's at all an option, you should use Joda-Time.
Related questions
Why were most java.util.Date methods deprecated?
Are you taking time zone into consideration? I see you have BST right now, but what when BST is over? Do you still wish to use BST?
Anyway, I'd suggest you have a look at DateMidnight from JodaTime and use that.
Things may vary depending on how you want to handle the time zones. But in it's simplest form, it should be as simple as:
DateMidnight d = new DateMidnight(myObject.getDate());
If you must convert back go java.util.Date:
Date myDate = d.toDate();
myDate.setTime(myDate.getTime()-myDate.getTime()%86400000)
might do the trick. Talk about quick&dirty.
May I know what is the most efficient way to construct a date object using a specific day, month, and year.
Date(int year, int month, int day)
This construct is depreciated. Hence, what I usually do is:
Calendar calendar = Calendar.getInstance();
Date date = calendar.set(year, month, date).getTime();
However, my understanding is that Calendar.getInstance() is rather expensive. What is the most efficient way to construct a Date object? Or should I just use Date(int year, int month, int day) quietly without telling the rest?
Please don't suggest using any third-party library.
With this you can avoid the innecesary "now time" instance creation.
Date coolDate = new GregorianCalendar(year, month, day).getTime();
You can check GregorianCalendar javadoc for other constructors. You have date+time, and timezone.
Anyway I agree with Jon Skeet that it's not so expensive. I agree with you that code doesn't need a default "now" initialization.
"Rather expensive" is somewhat vague. Have you actually tried using the code you've supplied, measured it and found it to be too expensive? Do you have a concrete idea of how cheap you need this operation to be?
Also, you haven't specified which time zone you want the value in the Date to represent. UTC? The default time zone? What time of day do you want it to be - midnight, or the current time of day? Your current code will keep the existing time of day - is that really what you want?
(As I mentioned in a comment, I would strongly suggest you move to Joda Time - but even if you don't, you should still check whether or not you've actually got a problem with your existing code before looking for a solution.)
I would simply do this:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date thisDate = formatter.parse("2010-03-04");
It's pretty efficient from a lines of code standpoint; I can't speak to its runtime efficiency vis a vis Calendar.
Ten years later in 2020: the only right answer is to use classes in java.util.time package.
LocalDate localDate = LocalDate.now();
LocalDate.of(2020, 3, 7);
LocalDate.parse("2020-03-07");
Whatever you use, as long as it's in the Java Standard API, it will involve the use of Calendar (both the Date constructor and SimpleDateFormat use it internally), so there's no point fretting about that class's supposed inefficiency.
I'm trying to do something really simple, but starting to realize that dates in Java are a bit of minefield. All I want is to get passed groups of three ints ( a year, a month and a date) create some Date objects, do some simple test on them (along the lines of as date A before date B and after January 1 1990), convert them to java.sql.Date objects and pass them off to the database via JDBC.
All very simple and works fine using the java.util.Date(int year,int month,int day) constructor. Of course that constructor is depreciated, and I'd like to avoid using depreciated calls in new code I'm writing. However all the other options to solve this simple problem seem stupidly complicated. Is there really no simple way to do what I want without using depreciated constructors?
I know the standard answer to all Java date related questions is "use joda time", but I really don't want to start pulling in third party libraries for such a seemingly trivial problem.
The idea is to use the Calendar class, like so:
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
Date date = cal.getTime();
Indeed, if you check the Javadoc of the constructor you are mentioning, it is exactly what is suggested:
Date(int year, int month, int date)
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Or ... use JodaTime :-).
Well, you can use the deprecated constructor. It has been deprecated for over 13 years and still works - it isn't going anywhere. If you don't want to do that and don't want to use a third party library, you have to use Calendar.
In Java 7, hopefully there will be a new time API, and you won't have the need for a third party API anymore.
LG's answer is valid but in general you should use Calendar for all your date operations and leave Date out of it unless your API requires it explicitly. In that case you can just convert it when passing it to the API.