Edmund Rojas
Edmund Rojas

Reputation: 6606

how to manipulate a Date object in java

I would like to take a date object like "Sat Feb 17 20:49:54 +0000 2007" and change the year variable to the current year dynamically to something like this "Sat Feb 17 20:49:54 +0000 2012" what would be the best way to do this in java?

Upvotes: 0

Views: 849

Answers (4)

Vineet Bhatia
Vineet Bhatia

Reputation: 2533

Another option would be to utilize JodaTime API

import org.joda.time.DateTime;
import org.joda.time.MutableDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class App
{
    public static void main( String[] args )
    {
        //Sat Feb 17 20:49:54 +0000 2007
        DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE MMM dd H:m:s Z yyyy");
        DateTime dt = fmt.parseDateTime("Sat Feb 17 20:49:54 +0000 2007");
        MutableDateTime mdt = dt.toMutableDateTime();
        mdt.setYear(new DateTime().getYear());

        System.out.println(fmt.print(mdt));
    }
}

Upvotes: 0

bchetty
bchetty

Reputation: 2241

Based on what you asked for, this is how you do that:

try {
    DateFormat dateFormat = new SimpleDateFormat("E, dd MMM HH:mm:ss Z yyyy");
    date = (Date) dateFormat.parse("Sat, Feb 17 20:49:54 +0000 2007");
    Calendar cal = dateFormat.getCalendar();
    cal.set(Calendar.YEAR, 2012);
} catch (ParseException pe) {
    //ParseException Handling
} catch(Exception e) {
    //Exception Handling
}

Upvotes: 0

evanwong
evanwong

Reputation: 5134

If that's already a date object, you can do this:

Calendar cal = Calendar.getInstance();
int currentYear = cal.get(Calendar.YEAR);
cal.setTime(dateObj);
//set the year to current year
cal.set(Calendar.YEAR, currentYear);
//new date object with current year
dateObj = cal.getTime();

If that's a string, you can parse the string to a Java Date object first using SimpleDateFormat: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html And the use the above calendar object.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691805

Construct a Calendar from the Date, use the Calendar to set the year, and then get back a Date object from the Calendar.

Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.YEAR, 2012);
date = c.getTime();

Upvotes: 4

Related Questions