Get Date in Java given Week number, week day and year - java

Given Week of the year, the week day and the year, how can we get the Date in Java?
With Jodatime, I tried the following:
DateTime dt = new DateTime();
dt.withYear(year);
dt.withWeekOfWeekyear(weekOfYear);
dt.withDayOfWeek(weekDay);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyMMdd");
System.out.println(dateTimeFormatter.print(dt));
But it gets the current Date!

JodaTime returns a changed copy, so do:
DateTime dt = new DateTime()
.withWeekyear(year)
.withWeekOfWeekyear(weekOfYear)
.withDayOfWeek(weekDay);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyMMdd");
System.out.println(dateTimeFormatter.print(dt));
And this should work as expected.

The accepted answer has bug..withYear(year) should be withWeekyear(year). #Neet please update it.

You need to reassign the date afterwards!
the dt.with*() methods simply make a copy of the date.
try
DateTime dt = new DateTime();
dt = dt.withYear(year);
dt = dt.withWeekOfWeekyear(weekOfYear);
dt = dt.withDayOfWeek(weekDay);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyMMdd");
System.out.println(dateTimeFormatter.print(dt));

We can also use this native java code using Calendar class:
SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, 23);
cal.set(Calendar.DAY_OF_WEEK, 3);
cal.set(Calendar.YEAR,2013);
System.out.println(sdf.format(cal.getTime()));

Here is a simple example of how to do it without JodaTime:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Snippet {
public static void main(String args[]) {
String year = "2013";
String week_of_year = "46";
String day_of_week = "4";
String yearweekday = year + week_of_year + day_of_week;
SimpleDateFormat sdf = new SimpleDateFormat("yyyywwu");
Date date = null;
try {
date = sdf.parse(yearweekday);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
}
}
Good luck!

tl;dr
YearWeek.of( 2017 , 1 )
.atDay( DayOfWeek.TUESDAY )
.format( DateTimeFormatter.ofPattern( "uuMMdd" ) )
“Week” ambiguous
The word 'week' is ambiguous. Do you mean week number 1 contains January 1? Or week number 1 contains the first of a particular day of year such as Sunday or Monday?
Or do you mean a standard ISO 8601 week? To quote from YearWeek doc:
ISO-8601 defines the week as always starting with Monday. The first week is the week which contains the first Thursday of the calendar year. As such, the week-based-year used in this class does not align with the calendar year.
java.time
The modern approach uses the java.time classes.
The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
ThreeTen-Extra
The ThreeTen-Extra project extends java.time with additional functionality. This includes a handy YearWeek class, just what we need for this Question.
Specify your week-based year number and your week number.
YearWeek yw = YearWeek.of( 2017 , 1 ) ;
The LocalDate class represents a date-only value without time-of-day and without time zone.
You can ask the YearWeek object to determine the date of a day contained within its week. Specify a DayOfWeek enum object. Note that a DayOfWeek is an object rather than a mere integer or string, providing for type-safety and valid values.
LocalDate ld = yw.atDay( DayOfWeek.TUESDAY ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

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.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
int weekNumber = 34;
int year = 2021;
System.out.println(getLocalDate(weekNumber, DayOfWeek.TUESDAY, year, Locale.UK));
System.out.println(getLocalDate(weekNumber, DayOfWeek.TUESDAY, year, Locale.US));
System.out.println(getLocalDate(weekNumber, DayOfWeek.SUNDAY, year, Locale.UK));
System.out.println(getLocalDate(weekNumber, DayOfWeek.SUNDAY, year, Locale.US));
}
static LocalDate getLocalDate(int weekNumber, DayOfWeek dow, int year, Locale locale) {
return LocalDate.of(year, 2, 1)
.with(dow)
.with(WeekFields.of(locale).weekOfWeekBasedYear(), weekNumber);
}
}
Output:
2021-08-24
2021-08-17
2021-08-29
2021-08-15
ONLINE DEMO
Note that the first day of the week is Locale-dependent e.g. it is Monday in the UK while Sunday in the US. As per the ISO 8601 standards, it is Monday. For comparison, check the US calendar and the UK calendar. Accordingly, the date will vary as shown in the example above.
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.

Related

parsing SimpleDateFormat to JodaTime

im creating a date from weeknumber, and a day of the week only. this I have successfully done with SimpleDateFormat, but i want to save it as jodatime, i have tried many things, but nothing that really worked.
This is my code so far.
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, week_of_year);
cal.set(Calendar.DAY_OF_WEEK, day_of_week);
sdf.format(cal.getTime());
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
DateTime jodatime = dtf.parseDateTime(sdf.toString());
I would like to get a jodatime så that my calendar kan sort objects based on the date, the time inst necessary.
When I run the code and want to display the jodatime, I get this error:
java.lang.IllegalArgumentException: Invalid format: "java.text.SimpleDateFormat#b93b42a0"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:945)
at com.example.casper.autimeplan.Fragments.ScheduleFragment$MyJavaScriptInterface.getBasicInfo(ScheduleFragment.java:282)
at com.example.casper.autimeplan.Fragments.ScheduleFragment$MyJavaScriptInterface.access$400(ScheduleFragment.java:186)
at com.example.casper.autimeplan.Fragments.ScheduleFragment$MyJavaScriptInterface$1.run(ScheduleFragment.java:203)
tl;dr
LocalDate.now().with( WeekFields.ISO.weekOfWeekBasedYear(), weekOfYear )
.with( WeekFields.ISO.dayOfWeek(), dayOfWeek )
java.time
Do not use the troublesome old date-time classes. Also, the Joda-Time project, now in maintenance mode, advises migration to the java.time classes. For Android, see the ThreeTenABP project mentioned in last bullets below.
You have not defined what you mean by week number. There are many ways to define a week of year. I will assume you meant the standard ISO 8601 definition of week # 1 having the first Thursday of the calendar, and Monday being the first day of every week.
Use the WeekFields class, specifically the WeekFields.ISO object.
long weekOfYear = 27 ; // 1-52 or 1-53 for ISO 8601 week-based years.
long dayOfWeek = 2 ; // 1-7 for Monday-Sunday, per ISO 8601 standard.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
LocalDate adjusted = today.with( WeekFields.ISO.weekOfWeekBasedYear(), weekOfYear )
.with( WeekFields.ISO.dayOfWeek(), dayOfWeek ) ;
Dump to console.
System.out.println( "2017-W27-02: " + adjusted ) ;
2017-W27-02: 2017-07-04
See this code run live at IdeOne.com.
By the way… While not back-ported to older Android, other Java platforms can use the nifty YearWeek class in the ThreeTen-Extra library for this kind of work.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
You are simply passing toString of object which won't work.
try something like this
private static String parseDateTime(String input){
String pattern = "MM/dd/yyyy HH:mm:ss";
DateTime dateTime = DateTime.parse(input, DateTimeFormat.forPattern(pattern));
return dateTime.toString("MM/dd/yyyy HH:mm:ss");
}
Read more here

Get last day of specific(SEPTEMBER) month

How to get the fiscal year end date (2017-09-30) dynamically.
Based on the year I need to get the fiscal year end date dynamically.
For example:
If 2017 then output should be 2017-09-30
If 2018 then output should be 2018-09-30 and so on.
Code:
Calendar.getInstance().getActualMaximum(Calendar.SEPTEMBER);
Output I am getting as "4"
Can I know how to get the end date dynamically.
This will help you
private static String getDate(int month, int year) {
Calendar calendar = Calendar.getInstance();
// passing month-1 because 0-->jan, 1-->feb... 11-->dec
calendar.set(year, month - 1, 1);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
Date date = calendar.getTime();
DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");
return DATE_FORMAT.format(date);
}
Fiscal year?
The term “fiscal year” is not defined here. Usually that is a company-specific definition, and may not be as simple as “end of September”.
Avoid legacy date-time classes
If you are asking for the same month and same day-of-month but adjusted by year, use the java.time classes. The troublesome Calendar class is now legacy, and should be avoided.
LocalDate & MonthDay
The LocalDate class represents a date-only value without time-of-day and without time zone.
The MonthDay class represents a month and day-of-month without any year and without any time zone.
LocalDate ld = LocalDate.of( 2017 , Month.SEPTEMBER , 30 );
MonthDay md = MonthDay.from( ld );
LocalDate ldInAnotherYear = md.atYear( ld.getYear() + 1 );
You could also simply add a year depending on the date in question and what your desired behavior is for handling the last days of a month since months have different lengths, and of course February has the issue of Leap Year.
LocalDate yearLater = LocalDate.of( 2017 , Month.SEPTEMBER , 30 ).plusYears( 1 );
YearMonth
You might find the YearMonth class handy. You can ask it for the last day of the month.
YearMonth ym = YearMonth( 2017 , Month.SEPTEMBER );
LocalDate endOfMonth = ym.atEndOfMonth();
I recommend using objects rather than mere integers. Consider passing around objects such as YearMonth, MonthDay, LocalDate, and Month where appropriate rather than numbers.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

store current date and date 1 year from current in java

I have everything setup already to store the current date to a variable in Java. What I am trying to figure out is how to store a date of 1 year after the current date.
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Scanner;
import java.util.Calendar;
Here is what I have for the current date:
DateFormat newDate = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
startDate = newDate.format(date);
So if it were today for example it would store 2/18/2013. I am trying to store the date 2/18/2014. How would I go about doing this?
If you do not want to drag external libraries, just use calendar.add(Calendar.YEAR, 1)
Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
cal.add(Calendar.YEAR, 1); // to get previous year add -1
Date nextYear = cal.getTime();
Note, if the date was 29/Feb/2012 and you added 1 year, you will get 28/Feb/2013
tl;dr
LocalDate.parse(
"2/18/2013" ,
DateTimeFormatter.ofPattern ( "M/d/uuuu" )
).plusYears( 1 )
Details
The accepted Answer is correct, but outdated as of Java 8.
java.time
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
LocalDate
These new classes include LocalDate, to represent a date-only value with no time-of-day nor time zone.
First we must parse the String input. The java.time formatter uses pattern codes similar to the old classes, but not exactly the same. So be sure to read the new doc carefully.
Padded Zero
Notice that your input String lacks leading zero digit for some values. That means you should use single pattern codes, M and d rather than MM and dd. Double codes means you expect padding zero to always be included for otherwise single-digit values, 02 rather than 2.
String input = "2/18/2013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "M/d/uuuu" );
LocalDate localDate = LocalDate.parse ( input , formatter );
Add a year. The java.time framework takes care of leap year.
LocalDate yearLater = localDate.plusYears ( 1 );
Dump to console.
System.out.println ( "localDate: " + localDate + " and yearLater: " + yearLater );
localDate: 2013-02-18 and yearLater: 2014-02-18
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Use Calendar#add(int field, int amount) method.You should use Calendar API in-order to manipulate date and time operations.
Calendar today = Calendar.getInstance();
Calendar nextYearToday = today;
nextYearToday.add(Calendar.YEAR, 1);
Calendar cal = Calendar.getInstance();
Date today = cal.getTime();
cal.add(Calendar.YEAR, 1); // to get previous year add 1
cal.add(Calendar.DAY_OF_MONTH, -1); // to get previous day add -1
Date expiryDate = cal.getTime();
System.out.println("today is --> "+today);
System.out.println("expiryDate is --> "+expiryDate);
OutPut
today is --> Fri Dec 01 10:10:52 GMT+05:30 2017
expiryDate is --> Fri Nov 30 10:10:52 GMT+05:30 2018
date today is -> Fri Dec 01 10:10:52 GMT+05:30 2017
expiryDate is -> Fri Nov 30 10:10:52 GMT+05:30 2018
In Android is simpler than ever:
oneYearAfterDate = new Date(date.getTime() + DateUtils.YEAR_IN_MILLIS )

Java: Get month Integer from Date

How do I get the month as an integer from a Date object (java.util.Date)?
java.util.Date date= new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
java.time (Java 8)
You can also use the java.time package in Java 8 and convert your java.util.Date object to a java.time.LocalDate object and then just use the getMonthValue() method.
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int month = localDate.getMonthValue();
Note that month values are here given from 1 to 12 contrary to cal.get(Calendar.MONTH) in adarshr's answer which gives values from 0 to 11.
But as Basil Bourque said in the comments, the preferred way is to get a Month enum object with the LocalDate::getMonth method.
If you use Java 8 date api, you can directly get it in one line!
LocalDate today = LocalDate.now();
int month = today.getMonthValue();
Joda-Time
Alternatively, with the Joda-Time DateTime class.
//convert date to datetime
DateTime datetime = new DateTime(date);
int month = Integer.parseInt(datetime.toString("MM"))
…or…
int month = dateTime.getMonthOfYear();
tl;dr
myUtilDate.toInstant() // Convert from legacy class to modern. `Instant` is a point on the timeline in UTC.
.atZone( // Adjust from UTC to a particular time zone to determine date. Renders a `ZonedDateTime` object.
ZoneId.of( "America/Montreal" ) // Better to specify desired/expected zone explicitly than rely implicitly on the JVM’s current default time zone.
) // Returns a `ZonedDateTime` object.
.getMonthValue() // Extract a month number. Returns a `int` number.
java.time Details
The Answer by Ortomala Lokni for using java.time is correct. And you should be using java.time as it is a gigantic improvement over the old java.util.Date/.Calendar classes. See the Oracle Tutorial on java.time.
I'll add some code showing how to use java.time without regard to java.util.Date, for when you are starting out with fresh code.
Using java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime.
The Month class is a sophisticated enum to represent a month in general. That enum has handy methods such as getting a localized name. And rest assured that the month number in java.time is a sane one, 1-12, not the zero-based nonsense (0-11) found in java.util.Date/.Calendar.
To get the current date-time, time zone is crucial. At any moment the date is not the same around the world. Therefore the month is not the same around the world if near the ending/beginning of the month.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or 'ZoneOffset.UTC'.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Month month = now.getMonth();
int monthNumber = month.getValue(); // Answer to the Question.
String monthName = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
If you can't use Joda time and you still live in the dark world :) ( Java 5 or lower ) you can enjoy this :
Note: Make sure your date is allready made by the format : dd/MM/YYYY
/**
Make an int Month from a date
*/
public static int getMonthInt(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
return Integer.parseInt(dateFormat.format(date));
}
/**
Make an int Year from a date
*/
public static int getYearInt(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
return Integer.parseInt(dateFormat.format(date));
}
If we use java.time.LocalDate api, we can get month number in integer in single line:
import java.time.LocalDate;
...
int currentMonthNumber = LocalDate.now().getMonthValue(); //OR
LocalDate scoringDate = LocalDate.parse("2022-07-01").getMonthValue(); //for String date
For example today's date is 29-July-2022, output will be 7.
Date mDate = new Date(System.currentTimeMillis());
mDate.getMonth() + 1
The returned value starts from 0, so you should add one to the result.

How to convert date from MM/YYYY to MM/DD/YYYY in Java

I want to convert date from MM/YYYY to MM/DD/YYYY, how i can do this using SimpleDateFormat in Java? (Note: DD can be start date of that month)
please go through the http://download.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html following link for more clarity.
One way of implementation i have in my mind is :
String yourDate = <yourDate>
DateFormat dateFormat= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date= new Date();
date = (Date)dateFormat.parse(yourDate);
//String dateString= dateFormat.format(date);
/*Print your date*/
Please go through this link SimpleDateFormat
try {
String str_date = "01/11";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("MM/yyyy");
date = (Date) formatter.parse(str_date);
formatter = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Today is " + formatter.format(date));
} catch (ParseException e) {
System.out.println("Exception :" + e);
}
The simplest approach is using string manipulation.
String date1 = "12/2010";
String date2 = date1.replace("/","/01/");
tl;dr
YearMonth.parse(
"12/2016" ,
DateTimeFormatter.ofPattern( "MM/uuuu" ) )
)
.atDay( 1 )
.format( DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) ) // 12/01/2016
java.time
Java now includes the YearMonth class to represent exactly this kind of value, a month and a year without a day-of-month.
The default format for parsing/generating strings of a month-year is YYYY-MM. That format is defined as part of the ISO 8601 format. The java.time classes use ISO 8601 formats by default.
Your input string has alternate format so we must specify a formatting pattern.
String input = "12/2016" ; // December 2016.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/uuuu" );
YearMonth ym = YearMonth.parse( input , f );
See the results by calling toString.
String output = ym.toString();
2016-12
Specify a day-of-month to create a LocalDate instance. The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = ym.atDay( 1 );
You can let the class figure out the last day of the month. Remember that February varies in length for Leap Year. The YearMonth class knows how to handle Leap Year.
LocalDate ld = ym.atEndOfMonth();
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
FYI, Java has a similar class, MonthDay.

Categories