Reputation: 29
I have two numbers. First would be the month number. Second would be the day number.
I also know the year.
How can I take those two number, month and day and make it into a single number DAY_OF_YEAR?
I'm using Java 1.7 and the Calendar functions.
Upvotes: 0
Views: 1641
Reputation: 5459
Just using calendar and assuming by number of month you mean the zero-indexed one where 0
means January, here is an example for May 13th 2019:
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.ENGLISH);
c.set(Calendar.YEAR, 2019);
c.set(Calendar.MONTH, 4);
c.set(Calendar.DAY_OF_MONTH, 13);
System.out.println(c.get(Calendar.DAY_OF_YEAR));
Edit: As Ole V.V.'s answer pointed out you get a Calendar object with the system's timezone if you call 'Calendar.getInstance()', so I changed it that way that you explicitly specify the timezone and Locale to be used. The latter is important if you e.g. want to get a date's week number where the rules differ in different regions of the world.
Upvotes: 0
Reputation: 86324
int year = 2019;
int monthNumber = 9;
int dayNumber = 28;
LocalDate date = LocalDate.of(year, monthNumber, dayNumber);
int dayOfYear = date.getDayOfYear();
System.out.println("Day of year is " + dayOfYear);
Output from this snippet is:
Day of year is 271
Tested on Java 1.7.0_79 using ThreeTen Backport 1.3.6 and importing org.threeten.bp.LocalDate
.
Four lines of the currently accepted answer creating and setting the Calendar
object are substituted by just one line here. It’s typical for code using Calendar
to be so wordy, which we shouldn’t want. Also despite the name a Calendar
object is more than a calendar date, it also carries with it a time of day, a time zone and more, so I do not consider it a good fit for the job at hand. The code using Calendar
will give a different result if the default locale is Thai, which will surprise most. The Calendar
class is poorly designed and long outdated.
Instead I am using LocalDate
of java.time, the modern Java date and time API.
I'm using Java 1.7 …
java.time works nicely on Java 7. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).Upvotes: 1
Reputation: 857
You can concat your parts into a String
, and use a SimpleDateFormatter
like:
int year = 2019;
int month = 1;
int day = 23;
String string = "" + year + "-" + month + "-" + day;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(string);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println(calendar.get(Calendar.DAY_OF_YEAR));
The example is for 2019 January 23.
Upvotes: 0