Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A point of clarification on Joda's DateTime

Tags:

java

jodatime

I'd like to do something like

private DateTime[] importantDates = {
        new DateTime(2013, 6, 15, 0, 0),
        new DateTime(2013, 9, 15, 0, 0)
};

Where year is always current year. Does Joda allow for something like this, without calculations?

Example: Right now we are living in 2013. I'd rather not hardcode this value.

For that matter, what i would really like it

private DateTime[] importantDates = {
        new DateTime(current_year, 6, 15),
        new DateTime(current_year, 9, 15),
};

Can this be done?

like image 208
James Raitsev Avatar asked Jan 14 '23 01:01

James Raitsev


1 Answers

Well the simplest approach would be:

int year = new DateTime().getYear();
DateTime[] dates = new DateTime[] {
    new DateTime(year, 6, 15, 0, 0),
    new DateTime(year, 9, 15, 0, 0),
};

That's not ideal for instance variables as it introduces an extra instance variable (year) for no good reason, but you could easily put it into a helper method:

private final DateTime[] importantDates = createImportantDatesThisYear();

private static DateTime[] createImportantDatesThisYear() {
    int year = new DateTime().getYear();
    return new DateTime[] {
        new DateTime(year, 6, 15, 0, 0),
        new DateTime(year, 9, 15, 0, 0),
    };
}

Note that all of this code assumes that you want

like image 96
Jon Skeet Avatar answered Jan 24 '23 13:01

Jon Skeet