jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Controlling a database item's life time Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Controlling a database item Watch "Controlling a database item New topic

Controlling a database item's life time

Jason Kwok
Ranch Hand

Joined: Mar 31, 2005
Posts: 126

I have a database that contains news items, among other things. When these news items are created and added to the database, the date they were created is recorded as well in medium format. Ex. 18-June-2006

My problem is that, I have written a servlet to retrieve news items and publish them on my homepage, however I need these news items to be removed after a certain life time. For example, to expire after 2 weeks.

How can I go about doing something like this? I know I could retrieve the current date and the creation date, but how can I find out how many days have passed between the two? I'd greatly appreciate any help with this!!

Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63838

Subtracting dates isn't really a Servlet issue so I've move this to Java in General (beginner)

[Asking smart questions] [About Bear] [Books by Bear]
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

Class java.util.Calendar contains methods to do date arithmetic. You can for example use the method add(...) to add or subtract a number of hours, days, months etc. from a date, and you can use the methods before(...) or after(...) to find out if a date is before or after another date.

With the combination of those methods, you can solve the problem.

Have a look at the API documentation of java.util.Calendar.

You could also do this in SQL; if you really want to delete items older than two weeks, run an SQL statement like "delete from newsitems where timestamp ..." (you'll have to find out the exact SQL yourself; read the SQL reference documentation of your database).
[ June 19, 2006: Message edited by: Jesper Young ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link: http://aspose.com/file-tools
subject: Controlling a database item's life time
It's not a secret anymore!