I want to get the day of week from the Java Date object when I have an array of Date in String with me.
SimpleDateFormat sourceDateformat = new SimpleDateFormat("yyyy-MM-dd");
public String[] temp_date;
public Int[] day = new Int[5];
Date[] d1= new Date[5];
Calendar[] cal= new Calendar[5]
try {
d1[i]= sourceDateformat.parse(temp_date[i].toString());
cal[i].setTime(d1[i]); // its not compiling this line..showing error on this line
day[i]= cal[i].get(Calendar.DAY_OF_WEEK);
}
catch (ParseException e) {
e.printStackTrace();
}
Does anyone know the answer to this?
You can get the day-integer like that:
Calendar c = Calendar.getInstance();
c.setTime(yourdate); // yourdate is an object of type Date
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); // this will for example return 3 for tuesday
If you need the output to be "Tue" rather than 3, instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version")
Taken from here: How to determine day of week by passing specific date?
// kotlin
val calendar = Calendar.getInstance()
val dateInfo = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.time)
data.text = dateInfo
java.time
You can do it using DateTimeFormatter.ofPattern("EEEE"):
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(getWeekDayName("2021-04-30"));
}
public static String getWeekDayName(String s) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d", Locale.ENGLISH);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("EEEE", Locale.ENGLISH);
return LocalDate.parse(s, dtfInput).format(dtfOutput);
}
}
Output:
Friday
Alternatively, you can get it using LocalDate#getDayOfWeek:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(getWeekDayName("2021-04-30"));
}
public static String getWeekDayName(String s) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d", Locale.ENGLISH);
return LocalDate.parse(s, dtfInput).getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
}
}
Output:
Friday
Learn more about the 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.
This is one of the many things that have become a lot easier with the advent of java.time, the modern Java date and time API.
String tempDate = "2020-03-29";
LocalDate date = LocalDate.parse(tempDate);
DayOfWeek day = date.getDayOfWeek();
System.out.println(day);
Output:
SUNDAY
Of course we now have got an enum for the days of the week. There’s no longer any reason to fiddle with integers and having to remember on what day of week they begin and whether the days are numbered from 0 or 1.
I am expoiting the fact that your expected input format (yyyy-MM-dd in your code) is ISO 8601, the default for java.time, so we don’t need to specify any formatter explicitly.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
In Kotlin, just do this:
val yourDateStr = "2021-01-01"
val df = DateFormat.parse(yourDateStr)
val weedDay = df.getWeekDay(yourTimeZone)
the below code works, depending on what number you enter in the DAY_OF_WEEK, that returns the specific weekday, in this example it always returns a future date and day will always be Tuesday.
DAY_OF_WEEK
public static String getTodaysDateAndTime(){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 5);
cal.add(Calendar.DAY_OF_WEEK, 2);
Date date = cal.getTime();
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String futureDate = dateformat.format(date);
System.out.println(futureDate);
return futureDate;
}
Related
My Android app wants to display a date-time string and the corresponding format string.
It uses the SimpleDateFormat because it is compatible with old Android API levels.
Calendar calendar=Calendar.getInstance();
formatString=getTheCurrentLocaleDateTimeFormatString();
SimpleDateFormat dateFormat = new SimpleDateFormat(formatString);
localeTimeString= dateFormat.format(calendar.getTimeInMillis());
displayToTheUser(localeTimeString);
displayToTheUser(formatString);
for example the user gets: "Wed, 4 Jul 2001 12:08:56" and "EEE, d MMM yyyy HH:mm:ss"
The provided code snippet is intended to get the date time form according to the current Locale but I do not know how to get it also as a format string. It should be calculated by the getTheCurrentLocaleDateTimeFormatString() method above.
I see that many format string patterns are available.
This is the relevant documentation page:
https://developer.android.com/reference/java/text/SimpleDateFormat#examples
Being that I want to display that format string to the user as a template and use it as a parameter for SimpleDateFormat my question is: how do I obtain the date time pattern format string of the current Locale?
You can do it as follows:
SimpleDateFormat getTheCurrentLocaleDateTimeFormatString() {
return (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault());
}
A test program:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = getTheCurrentLocaleDateTimeFormatString();
String localeTimeString = dateFormat.format(calendar.getTimeInMillis());
System.out.println(localeTimeString);
}
static SimpleDateFormat getTheCurrentLocaleDateTimeFormatString() {
return (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault());
}
}
Output:
Sunday, 12 January 2020
[Update]
Posting the following code based on your comment:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Calendar calendar=Calendar.getInstance();
String formatString=getTheCurrentLocaleDateTimeFormatString();
System.out.println(formatString);
SimpleDateFormat dateFormat = new SimpleDateFormat(formatString);
String localeTimeString= dateFormat.format(calendar.getTimeInMillis());
System.out.println(localeTimeString);
}
static String getTheCurrentLocaleDateTimeFormatString() {
return ((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault())).toLocalizedPattern();
}
}
Output:
EEEE, d MMMM y
Sunday, 12 January 2020
[Another update]
Posting the following code based on your another comment:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
String formatString = getTheCurrentLocaleDateTimeFormatString();
System.out.println(formatString);
SimpleDateFormat dateFormat = new SimpleDateFormat(formatString);
String localeTimeString = dateFormat.format(calendar.getTimeInMillis());
System.out.println(localeTimeString);
}
static String getTheCurrentLocaleDateTimeFormatString() {
return ((SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL,
Locale.getDefault())).toLocalizedPattern();
}
}
Output:
EEEE, d MMMM y 'at' HH:mm:ss zzzz
Sunday, 12 January 2020 at 20:28:05 Greenwich Mean Time
java.time and ThreeTenABP
Code using java.time. the modern Java date and time API, can be made to work on old Android API levels too. DateTimeFormatterBuilder.getLocalizedDateTimePattern() gives you the format pattern string that you asked for. For example:
ZonedDateTime dateTIme = ZonedDateTime.now(ZoneId.of("America/Recife"));
Locale userLocale = Locale.forLanguageTag("pt-BR");
String formatPattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.LONG, FormatStyle.LONG,
IsoChronology.INSTANCE, userLocale);
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern(formatPattern, userLocale);
String localeTimeString = dateTIme.format(formatter);
System.out.println(localeTimeString);
System.out.println(formatPattern);
Just now the output from this snippet was:
12 de Janeiro de 2020 17h7min52s BRT
d' de 'MMMM' de 'yyyy H'h'm'min's's' z
The apostrophes in the format pattern enclose literal parts so de, h, min and s are not taken to be format pattern letters, but are output literally in the formatted date and time.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
I have two Date objects with the below format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String matchDateTime = sdf.parse("2014-01-16T10:25:00");
Date matchDateTime = null;
try {
matchDateTime = sdf.parse(newMatchDateTimeString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// get the current date
Date currenthDateTime = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date dt = new Date();
String currentDateTimeString = dateFormat.format(dt);
Log.v("CCCCCurrent DDDate String is:", "" + currentDateTimeString);
try {
currenthDateTime = sdf.parse(currentDateTimeString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now I want to compare the above two dates along with time.
How should I compare in Java.
Thanks
Since Date implements Comparable<Date>, it is as easy as:
date1.compareTo(date2);
As the Comparable contract stipulates, it will return a negative integer/zero/positive integer if date1 is considered less than/the same as/greater than date2 respectively (ie, before/same/after in this case).
Note that Date has also .after() and .before() methods which will return booleans instead.
An Alternative is....
Convert both dates into milliseconds as below
Date d = new Date();
long l = d.getTime();
Now compare both long values
Use compareTo()
Return Values
0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
Like
if(date1.compareTo(date2)>0)
An alternative is Joda-Time.
Use DateTime
DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();
// Get calendar set to the current date and time
Calendar cal = Calendar.getInstance();
// Set time of calendar to 18:00
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// Check if current time is after 18:00 today
boolean afterSix = Calendar.getInstance().after(cal);
if (afterSix) {
System.out.println("Go home, it's after 6 PM!");
}
else {
System.out.println("Hello!");
}
The other answers are generally correct and all outdated. Do use java.time, the modern Java date and time API, for your date and time work. With java.time your job has also become a lot easier compared to the situation when this question was asked in February 2014.
String dateTimeString = "2014-01-16T10:25:00";
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());
if (dateTime.isBefore(now)) {
System.out.println(dateTimeString + " is in the past");
} else if (dateTime.isAfter(now)) {
System.out.println(dateTimeString + " is in the future");
} else {
System.out.println(dateTimeString + " is now");
}
When running in 2020 output from this snippet is:
2014-01-16T10:25:00 is in the past
Since your string doesn’t inform of us any time zone or UTC offset, we need to know what was understood. The code above uses the device’ time zone setting. For a known time zone use like for example ZoneId.of("Asia/Ulaanbaatar"). For UTC specify ZoneOffset.UTC.
I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time parse the most common ISO 8601 variants without us having to give any formatter.
Question: For Android development doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
I have a ReST service which downloads information about events in a persons calendar...
When it returns the date and time, it returns them as a string
e.g. date = "12/8/2012" & time = "11:25 am"
To put this into the android calendar, I need to do the following:
Calendar beginTime = Calendar.getInstance();
beginTime.set(year, month, day, hour, min);
startMillis = beginTime.getTimeInMillis();
intent.put(Events.DTSTART, startMillis);
How can I split the date and time variables so that they are useable in the "beginTime.set() " method?
I don't thinks you really need how to split the string, in your case it should be 'how to get time in milliseconds from date string', here is an example:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateTest {
public static void main(String[] args) {
String date = "12/8/2012";
String time = "11:25 am";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
try {
Date dt = df.parse(date + " " + time);
Calendar ca = Calendar.getInstance();
ca.setTime(dt);
System.out.println(ca.getTimeInMillis());
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Try this:
String date = "12/8/2012";
String time = "11:25 am";
String[] date1 = date.split("/");
String[] time1 = time.split(":");
String[] time2 = time1[1].split(" "); // to remove am/pm
Calendar beginTime = Calendar.getInstance();
beginTime.set(Integer.parseInt(date1[2]), Integer.parseInt(date1[1]), Integer.parseInt(date1[0]), Integer.parseInt(time1[0]), Integer.parseInt(time2[0]));
startMillis = beginTime.getTimeInMillis();
intent.put(Events.DTSTART, startMillis);
Hope this helps.
Assuming you get your date in String format (if not, convert it!) and then this:
String date = "12/8/2012";
String[] dateParts = date.split("/");
String day = dateParts[0];
String month = dateParts[1];
Similarly u can split time as well!
You can see an example of split method here : How to split a string in Java
Then simply use the array for your parameter eg: array[0] for year and etc..
Use SimpleDateFormat (check api docs). If you provide proper time pattern it will be able to convert string into Date instantly.
This is just a Idea, you can do some thing like this without splitting
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm a");
Date date = formatter.parse("12/8/2012 11:25 am");
Calendar cal=Calendar.getInstance();
cal.setTime(date);
java.time either through desugaring or through ThreeTenABP
Consider using java.time, the modern Java date and time API, for your date and time work. With java.time it’s straightforward to parse your two strings for date and time individually and then combine date and time into one object using LoalDate.atTime().
The way I read your code you are really after a count of milliseconds since the epoch. So this is what I am giving you in the first snippet. Feel free to take it apart and use only the lines you need.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
DateTimeFormatter timeFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("h:mm a")
.toFormatter(Locale.ENGLISH);
String dateString = "12/8/2012";
String timeString = "11:25 am";
LocalDate date = LocalDate.parse(dateString, dateFormatter);
LocalTime time = LocalTime.parse(timeString, timeFormatter);
long startMillis = date
.atTime(time)
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();
System.out.println(startMillis);
When running in my time zone (at UTC offset +02:00 in August) the output is:
1344763500000
For anyone reading along that does need the individual numbers from the two strings, getting those is straightforward too. For example:
int year = date.getYear();
Month month = date.getMonth();
int monthNumber = date.getMonthValue();
int dayOfMonth = date.getDayOfMonth();
int hourOfDay = time.getHour();
int hourWithinAmOrPm = time.get(ChronoField.HOUR_OF_AMPM);
int minute = time.getMinute();
System.out.format("Year %d month %s or %d day %d hour %d or %d AM/PM minute %d%n",
year, month, monthNumber, dayOfMonth, hourOfDay, hourWithinAmOrPm, minute);
Year 2012 month AUGUST or 8 day 12 hour 11 or 11 AM/PM minute 25
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
there are two string
String date = "9/13/2012";
String time = "5:48pm";
the time is GMT+0, I wanna change it to GMT+8,what is the simplest way to change a time to particular timezone
Parse it using a SimpleDateFormat set to the UTC time zone
Format the parsed Date value using a SimpleDateFormat set to the time zone you're interested in. (It's likely to be something other than just "UTC+8" - you should find out which TZDB time zone ID you really want.
For example:
SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy h:mma", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC");
Date date = inputFormat.parse(date + " " + time);
// Or whatever format you want...
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
outputFormat.setTimeZone(targetTimeZone);
String outputText = outputFormat.format(date);
(If you can use Joda Time instead, that'd be great - but I understand that it's pretty big for an Android app.)
The Joda-Time library provides a good set of objects for working with dates/times in multiple time zones. http://joda-time.sourceforge.net/
Something like this for example:
String date = "9/13/2012";
String time = "5:48pm";
String[] dateParts = date.split("/");
Integer month = Integer.parseInt(dateParts[0]);
Integer day = Integer.parseInt(dateParts[1]);
Integer year = Integer.parseInt(dateParts[2]);
String[] timeParts = time.split(":");
Integer hour = Integer.parseInt(timeParts[0]);
Integer minutes = Integer.parseInt(timeParts[1].substring(0,timeParts[1].lastIndexOf("p")));
DateTime dateTime = new DateTime(year, month, day, hour, minutes, DateTimeZone.forID("Etc/GMT"));
dateTime.withZone(DateTimeZone.forID("Etc/GMT+8"));
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*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String date = "9/13/2012";
String time = "5:48pm";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u h:ma", Locale.UK);
LocalDateTime ldtSource = LocalDateTime.parse(date + " " + time, dtf);
OffsetDateTime odtSource = ldtSource.atOffset(ZoneOffset.UTC);
OffsetDateTime odtTarget = odtSource.withOffsetSameInstant(ZoneOffset.of("+08:00"));
System.out.println(odtTarget);
// In a custom format
System.out.println(odtTarget.format(dtf));
}
}
Output:
2012-09-14T01:48+08:00
9/14/2012 1:48am
ONLINE DEMO
Learn more about 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.
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?
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.
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.
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");