Britt
Britt

Reputation:

Convert to date

I'm trying to create number of Evenement instances and set the date for them:

   for (int i=2004; i<2009; i++){
           evenementen.add(new Evenement("Rock Werchter", "Rock", "Werchter", 200000,
                           (Date)formatter.parse(i+"/07/03")));

But I can't seem to get it to work,

Any ideas?

Upvotes: 1

Views: 321

Answers (3)

VonC
VonC

Reputation: 1324515

Beware of the locale used for the date formatter (default can be Locale.ENGLISH is your OS is set that way, meaning the year is at the end, not at the beginning of the string)

You need to be sure to have a formatter build as (at the time of writing, 2008, Java6, as in this answer):

formatter = new SimpleDateFormat("yyyy/MM/DD");

Upvotes: 2

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Solution using java.time, the modern API:

import java.time.LocalDate;
import java.time.Month;

public class Main {
    public static void main(String[] args) {
        for (int i = 2004; i < 2009; i++) {
            System.out.println(LocalDate.of(i, Month.JULY, 3));
        }
    }
}

If you want to do it by parsing the string (the way you have posted in the question), use DateTimeFormatter.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u/M/d", Locale.ENGLISH);
        for (int i = 2004; i < 2009; i++) {
            LocalDate date = LocalDate.parse(i + "/07/03", dtf);
            System.out.println(date);
        }
    }
}

Output:

2004-07-03
2005-07-03
2006-07-03
2007-07-03
2008-07-03

Learn more about java.time, the modern Date-Time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Upvotes: 3

Powerlord
Powerlord

Reputation: 88796

You may want to use Calendar to create your dates.

for (int i=2004; i<2009; i++) {
    Calendar cal = Calendar.getInstance();
    cal.clear();
    // Calendar.JULY may be different depending on the JDK language
    cal.set(i, Calendar.JULY, 3); // Alternatively, cal.set(i, 6, 3); 
    evenementen.add(new Evenement("Rock Werchter", "Rock", "Werchter", 200000,
            cal.getTime()));
}

Note that the months are zero-based, so July is 6.

Upvotes: 3

Related Questions