Sorry for my bad English,I have list of dates coming from json
{
"data": [
{
"lead_id": "1763",
"name": "Gaurav Kumar",
"date": "16-02-2020",
"time": "10:00 To 11:00 AM",
},
{
"lead_id": "1759",
"name": "Test",
"date": "04-02-2020",
"time": "10:00 To 11:00 AM",
},
{
"lead_id": "1751",
"name": "kavita sharma",
"date": "08-02-2020",
"time": "10:00 To 11:00 AM",
},
{
"lead_id": "1751",
"name": "kavita sharma",
"date": "09-02-2020",
"time": "10:00 To 11:00 AM",
}
]
}
Below code helps me to find the current date
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
#SuppressLint("SimpleDateFormat")
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
todayAsString = dateFormat.format(today);
System.out.println(todayAsString);
But i want to know how can i check if the list of date is of the same month.
//Here is the code the i used to check the current date but i want to check if the all dates is of the same months.PLease let me know how could i do this
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://delhidailyservice.com/api/")
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService request = retrofit.create(APIService.class);
Call<LeadData> call = request.leadData(prefConfig.readLoginId());
call.enqueue(new Callback<LeadData>() {
#Override
public void onResponse(Call<LeadData> call, Response<LeadData> response) {
/* new Handler().postDelayed(new Runnable() {
public void run() {
// if (isAdded()) {
pDialog.dismiss();
// }
}
}, 5000);*/
pDialog.dismiss();
LeadData allEvent = response.body();
allEventData = (List<Leads>) allEvent.getData();
// Log.d("Error", ""+allEventData.size());
allEventDatanew.clear();
for (int i = 0; i < allEventData.size(); i++) {
if (todayAsString.equalsIgnoreCase(allEventData.get(i).getDate())) {
Leads allevent = new Leads();
String service = allEventData.get(i).getService();
String date = allEventData.get(i).getDate();
String name = allEventData.get(i).getName();
String time = allEventData.get(i).getTime();
String city = allEventData.get(i).getCity();
String status = allEventData.get(i).getStatus();
String credit = allEventData.get(i).getCredit();
String address = allEventData.get(i).getAddress();
String id = allEventData.get(i).getLeadId();
try {
//String details = allEventData.get(i).getDetail();
//abcd = Html.fromHtml(details).toString();
// tv_detail.setText(abcd);
} catch (Exception e) {
e.printStackTrace();
}
allevent.setService(service);
allevent.setDate(date);
allevent.setName(name);
allevent.setTime(time);
allevent.setCity(address + " , " + city);
allevent.setStatus(status);
allevent.setCredit(credit);
allevent.setLeadId(id);
allEventDatanew.add(allevent);
}
}
// Log.d("Error1", ""+allEventDatanew.size());
individualDataAdapter = new LeadAdapter(allEventDatanew, getContext());
recyclerViewIndividualEvent.setAdapter(individualDataAdapter);
individualDataAdapter.notifyDataSetChanged();
java.time and ThreeTenABP
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
List<Leads> allEventData = Arrays.asList(new Leads("16-02-2020"),
new Leads("04-02-2020"), new Leads("08-02-2020"),
new Leads("09-02-2020"));
if (allEventData.isEmpty()) {
System.out.println("No data");
} else {
YearMonth month = YearMonth.parse(allEventData.get(0).getDate(), dateFormatter);
boolean otherMonthFound = false;
for (Leads lead : allEventData) {
if (! YearMonth.parse(lead.getDate(), dateFormatter).equals(month)) {
otherMonthFound = true;
break;
}
}
if (otherMonthFound) {
System.out.println("They are not all in the same month");
} else {
System.out.println("They are all in the same month " + month);
}
}
Output from this snippet is:
They are all in the same month 2020-02
I left out the other fields from the Leads class I used since they make no difference for the solution.
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.
LocalDate
The LocalDate class represents a date-only value, without time-of-day and without time zone or offset.
Tip: Educate the publisher of your data about the ISO 8601 standard for textual formats when exchanging date-time values. The date should be in format of YYYY-MM-DD. The time-of-day range should be in 24-clock, with the pair of times separated by a slash character, ex. 11:00/15:00.
Your input is non-standard, so we must specify a formatting pattern to match. We use DateTimeFormatter.
String input = "16-02-2020" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu` ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
YearMonth
The YearMonth class represents an entire month.
Getting the current month requires a time zone. For any given moment, the date varies around the globe by time zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
YearMonth ymCurrent = YearMonth.now( z ) ;
Get month of your input.
YearMonth ym = YearMonth.from( ld ) ;
Compare.
if( ym.equals( ymCurrent ) ) { … }
To see a further example of how to use this code to solve your problem, see the correct Answer by Ole V.V.
You can use this function
private void checkDate() {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
Date date = new Date();
String currentMonth = dateFormat.format(date);
Log.d("Current Month", dateFormat.format(date));
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject innerJsonObject = jsonArray.getJSONObject(i);
String jsonDate = innerJsonObject.getString("date");
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
Date modifiedDate = format.parse(jsonDate);
String monthString = (String) DateFormat.format("MM", modifiedDate);
if (TextUtils.equals(monthString, currentMonth)) {
Log.d(TAG, "Match " + jsonDate);
//TODO:
} else {
Log.d(TAG, "Mismatch " + jsonDate);
//TODO:
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Explanation
Initially, I have created a local variable currentMonth which gets the current month digit from the device.
I have parsed your JSON Array data and fetched the date value from the inner json object of the array.
I used SimpleDateFormat class to fetch the month part from the date value (modifiedDate) and stored it inside monthString.
This will return me the month value as String.
I have used String Comparison to verify whether the current month and the parsed month is same or not.
If you really want to know whether all the dates in the JSON Array of the current month or not, you can use this function
private boolean checkAllDates(String jsonData) throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
Date date = new Date();
String currentMonth = dateFormat.format(date);
JSONObject jsonObject = new JSONObject(jsonData);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject innerJsonObject = jsonArray.getJSONObject(i);
String jsonDate = innerJsonObject.getString("date");
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
Date modifiedDate = format.parse(jsonDate);
String monthString = (String) DateFormat.format("MM", modifiedDate);
if (!TextUtils.equals(monthString, currentMonth)) return false;
}
return true;
}
I need help in getting start and end date of current year, last year and next year.
Below is my code: this code is work fine for month, can I modify it for year?
Note: this code is only for example.
protected void getDataByMonths(int currentDayOfMonth) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month;
if (currentDayOfMonth >= 2) {
month = calendar.get(Calendar.MONTH) + 1;
} else {
month = calendar.get(Calendar.MONTH) - currentDayOfMonth;
}
int day = 1;
calendar.set(year, month, day);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
int numOfDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
String firstday = String.valueOf(df.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth - 1);
String lastday = String.valueOf(df.format(calendar.getTime()));
String result = getButtonName(button) + " From :" + getDateInMonthFormat(firstday) + " " + "To :" + getDateInMonthFormat(lastday);
finalcontacts = mySqliteDBhelper.getContactsBetweenRange(button, getDateInMilliseconds(firstday), getDateInMilliseconds(lastday));
finalstatus.setText(result);
}
Assuming that you cannot use Java 8, here is how it could be done:
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
// Create first day of year
Calendar firstDayOfCurrentYear = Calendar.getInstance();
firstDayOfCurrentYear.set(Calendar.DATE, 1);
firstDayOfCurrentYear.set(Calendar.MONTH, 0);
System.out.println(df.format(firstDayOfCurrentYear.getTime()));
// Create last day of year
Calendar lastDayOfCurrentYear = Calendar.getInstance();
lastDayOfCurrentYear.set(Calendar.DATE, 31);
lastDayOfCurrentYear.set(Calendar.MONTH, 11);
System.out.println(df.format(lastDayOfCurrentYear.getTime()));
// Create first day of next year
Calendar firstDayOfNextYear = Calendar.getInstance();
firstDayOfNextYear.add(Calendar.YEAR, 1);
firstDayOfNextYear.set(Calendar.DATE, 1);
firstDayOfNextYear.set(Calendar.MONTH, 0);
System.out.println(df.format(firstDayOfNextYear.getTime()));
// Create last day of next year
Calendar lastDayOfNextYear = Calendar.getInstance();
lastDayOfNextYear.add(Calendar.YEAR, 1);
lastDayOfNextYear.set(Calendar.DATE, 31);
lastDayOfNextYear.set(Calendar.MONTH, 11);
System.out.println(df.format(lastDayOfNextYear.getTime()));
Output:
01/01/2016
12/31/2016
01/01/2017
12/31/2017
Check this:
public static String GetYearSlot(int option,String inputDate)
{
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy",java.util.Locale.getDefault());
Date myDate = null;
try
{
myDate = sdf.parse(inputDate);
}
catch(Exception ex)
{
ex.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.YEAR, option);
calendar.set(Calendar.DAY_OF_YEAR, 1);
Date YearFirstDay = calendar.getTime();
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 31);
Date YearLastDay = calendar.getTime();
return sdf.format(YearFirstDay)+"-"+sdf.format(YearLastDay);
}
how to use:
GetYearSlot(1, fromDate): it gives you next year from the date you passed(input 1)
GetYearSlot(0, fromDate): it gives you current year from the date you passed(input 0)
GetYearSlot(-1, fromDate): it gives you previous year from the date you passed(input -1)
java.time
You are using troublesome old legacy date-time classes now supplanted by the java.time classes.
First get the current date.
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( “America/Montreal” );
LocalDate today = LocalDate.now( z );
Use Year to represent the entire year as an object.
Year thisYear = Year.from( today );
Year nextYear = thisYear.plusYears( 1 );
Year lastYear = thisYear.minusYears( 1 );
Usually in date-time work we represent a span of time using the Half-Open approach. In this approach the beginning is inclusive while the ending is exclusive. So a year would start on January first and run up to, but not include, January 1 of the following year.
If on Java 8, you could include the ThreeTen-Extra project and its Interval class to represent the span of time.
Otherwise do it yourself.
LocalDate thisYearStart = thisYear.atDay( 1 );
LocalDate lastYearStart = lastYear.atDay( 1 );
LocalDate nextYearStart = nextYear.atDay( 1 );
If you truly need the last day of the year, you could just subtract one day from the first day of the following year. Even easier is using a TemporalAdjuster defined in TemporalAdjusters class.
LocalDate thisYearFirstDay = today.with( TemporalAdjusters.firstDayOfYear() );
LocalDate thisYearLastDay = today.with( TemporalAdjusters.lastDayOfYear() );
LocalDate nextYearFirstDay = thisYearLastDay.plusDays( 1 );
LocalDate nextYearLastDay = nextYearFirstDay.with( TemporalAdjusters.lastDayOfYear() );
LocalDate lastYearLastDay = thisYearFirstDay.minusDays( 1 );
LocalDate lastYearFirstDay = lastYearLastDay.with( TemporalAdjusters.firstDayOfYear() );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
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.
This question already has answers here:
How to get the first date and last date of the previous month? (Java)
(9 answers)
Closed 4 years ago.
String febSt = "02/01/2014" ;
String febEnd = "02/28/2014" ;
Above code is my input i need "03/01/2014" and "03/31/2014" as output .
I tried more codes and used calendar functions also but no result.From this program i need next month start and end date .
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class MonthCalculation {
public void getNextMonth(String date) throws ParseException{
DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date dt = format.parse(date);
Date begining, end;
{
Calendar calendar = getCalendarForNow(dt);
calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setTimeToEndofDay(calendar);
end = calendar.getTime();
SimpleDateFormat endDt = new SimpleDateFormat("MM/dd/yyyy");
String endStrDt = endDt.format(end);
if(date != null && date.equalsIgnoreCase(endStrDt)){
System.out.println("Ending of the month");
calendar.add(Calendar.DAY_OF_MONTH, 1);
Date lastDate = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String lastDateofNextMonth = sdf.format(lastDate);
System.out.println("Next Month :"+lastDateofNextMonth);
Calendar c = getCalendarForNow(new Date(lastDateofNextMonth));
calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setTimeToEndofDay(calendar);
end = calendar.getTime();
SimpleDateFormat sfd = new SimpleDateFormat("MM/dd/yyyy");
String lastDated = endDt.format(end);
System.out.println("Testing side :"+lastDated);
}else if (findLeapYear(dt)){
Calendar calendar3 = getCalendarForNow(dt);
calendar3.add(Calendar.YEAR, 1);
Date ds = calendar3.getTime();
SimpleDateFormat dtft = new SimpleDateFormat("MM/dd/yyyy");
String dates = dtft.format(ds);
dtft.setLenient(false);
System.out.println("YEAR : "+dates);
}else{
SimpleDateFormat dtft = new SimpleDateFormat("MM/dd/yyyy");
Calendar calendar2 = getCalendarForNow(dt);
System.out.println(" Calendar time :->> " + dtft.format(calendar2.getTime()));
int curre_month = calendar2.get(Calendar.MONTH);
int curre_day = calendar2.get(Calendar.DAY_OF_MONTH);
int curre_year = calendar2.get(Calendar.YEAR);
Date dat = calendar2.getTime();
calendar2.add(Calendar.DATE, 31);
Date ds = calendar2.getTime();
String dates = dtft.format(ds);
dtft.setLenient(false);
System.out.println("OTHER DAYS : "+dates);
}
}
}
private static boolean findLeapYear(Date dt){
boolean isLeapYr = false;
int yr = dt.getYear();
if ((yr%4 == 0 && yr%100!=0)){
isLeapYr = true;
}
return isLeapYr;
}
private static Calendar getCalendarForNow(Date dt) {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(dt);
return calendar;
}
private static void setTimeToBeginningOfDay(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
}
private static void setTimeToEndofDay(Calendar calendar) {
System.out.println("For feb calling");
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
}
public static void main(String[] args) {
try {
String janSt = "01/01/2014" ;
String janEnd = "01/31/2014" ;
String febSt = "02/01/2014" ;
String febEnd = "02/28/2014" ;
String marSt = "03/01/2014" ;
String marEnd = "03/31/2014" ;
String aprilSt = "04/01/2014" ;
String aprilEnd = "04/30/2014" ;
String maySt = "05/01/2014" ;
String mayEnd = "05/31/2014" ;
String juneSt = "06/01/2014" ;
String juneEnd = "06/30/2014" ;
String julySt = "07/01/2014" ;
String julyEnd = "07/31/2014" ;
String augSt = "08/01/2014" ;
String augEnd = "08/31/2014" ;
String sepSt = "09/01/2014" ;
String sepEnd = "09/30/2014" ;
String octSt = "10/01/2014" ;
String octEnd = "10/31/2014" ;
String novSt = "11/01/2014" ;
String novEnd = "11/30/2014" ;
String deceSt = "12/01/2014" ;
String deceEnd = "12/31/2014" ;
String jan15St="01/01/2015";
String jan15End="01/31/2015";
String leapyr = "02/29/2016";
String notaleapyr = "02/28/2015";
new MonthCalculation().getNextMonth(febSt);
} catch (ParseException e) {
e.printStackTrace();
}
}
I tried more with sample inputs , for the months February ,april, june nov start date are not working if i pass these dates as inputs it returns with 2nd of next month
Suggest any idea to proceed further.I am struggling this code.
Thanks in advance
Try this:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date nextMonthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextMonthLastDay = calendar.getTime();
tl;dr
LocalDate.parse( "02/14/2014" , DateTimeformatter.ofPattern( "MM/dd/uuuu" ) )
.with( TemporalAdjusters.firstDayOfNextMonth() )
…and…
LocalDate.parse( "02/14/2014" , DateTimeformatter.ofPattern( "MM/dd/uuuu" ) )
.with( TemporalAdjusters.lastDayOfMonth() )
java.time
The modern way is with the new java.time package bundled with Java 8 (inspired by Joda-Time, defined by JSR 310).
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeformatter.ofPattern( "MM/dd/uuuu" );
LocalDate ld = LocalDate.parse( "02/14/2014" , f );
The TemporalAdjuster interface defines a way for implementations to manipulate date-time values. The TemporalAdjusters class provides several handy implementations.
LocalDate firstOfMonth = ld.with( TemporalAdjusters.firstDayOfMonth() );
LocalDate firstOfNextMonth = ld.with( TemporalAdjusters.firstDayOfNextMonth() );
The Question asks for the first and last of the following month, March in this case. We have the first of next month, so we just need the end of that month.
LocalDate lastOfNextMonth = firstOfNextMonth.with( TemporalAdjusters.lastDayOfMonth() );
By the way, as discussed below, the best practice for defining a span of time is the Half-Open approach. That means a month is the first of the month and running up to, but not including, the first of the month after. In this approach we do not bother with determining the last day of the month.
Joda-Time
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
Easy when using the Joda-Time library and its LocalDate class.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" );
LocalDate localDate = formatter.parseLocalDate( "02/14/2014" );
LocalDate firstOfMonth = localDate.withDayOfMonth( 1 );
LocalDate nextMonth = localDate.plusMonths(1); // Use this for "half-open" range.
LocalDate endOfMonth = nextMonth.minusDays(1); // Use this for "fully-closed" range.
Half-Open
Tip: Rather than focus on the last moment of a span of time, a better practice is to use the "Half-Open" approach.
In half-open, the beginning is inclusive and the ending is exclusive. So for "a month", we start with the first of the desired month and run up to, but not including, the first of the next month.
February 2014 = 2014-02-01/2014-03-01
Span Of Time
Be aware that Joda-Time provides three handy classes for handling a span of time: Interval, Period, and Duration.
These classes work only with date-time objects (DateTime class) rather than the date-only (LocalDate class) shown in code above.
While not directly relevant to your question, I suspect these span-of-time classes may be helpful.
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.
Something I quickly wrote for you - so could be cleaned up. Check if this helps:
String string = "02/01/2014"; //assuming input
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date dt = sdf .parse(string);
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.MONTH, 1); //adding a month directly - gives the start of next month.
String firstDate = sdf.format(c.getTime());
System.out.println(firstDate);
//get last day of the month - add month, substract a day.
c.add(Calendar.MONTH, 1);
c.add(Calendar.DAY_OF_MONTH, -1);
String lastDate = sdf.format(c.getTime());
System.out.println(lastDate);
since it is hard to get in your code I have write some coe for you. please check it out..
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
System.out.println("Today : " + sdf.format(today));
System.out.println("Last Day of Month: " + sdf.format(lastDayOfMonth));
I see the question is old. But I used the DateUtils static methods ceiling and truncate. Came in pretty handy instead of using multiple lines of code.
Date today = new Date();
DateUtils.truncate(new Date(), Calendar.MONTH) // Thu Dec 01 00:00:00 EET 2016
DateUtils.ceiling(new Date(), Calendar.MONTH) // Sun Jan 01 00:00:00 EET 2017
I recently came across a task where i have to get all Fridays in a date range. I wrote a small piece of code and was surprised see some strange behaviour.
Below is my code:
public class Friday {
public static void main(String[]args){
String start = "01/01/2009";
String end = "12/09/2013";
String[] startTokens = start.split("/");
String[] endTokens = end.split("/");
Calendar startCal = new GregorianCalendar(Integer.parseInt(startTokens[2]),Integer.parseInt(startTokens[1])-1,Integer.parseInt(startTokens[0]));
Calendar endCal = new GregorianCalendar(Integer.parseInt(endTokens[2]),Integer.parseInt(endTokens[1])-1, Integer.parseInt(endTokens[0]));
int startYear = Integer.parseInt(startTokens[2]);
int endYear = Integer.parseInt(endTokens[2]);
int startWeek = startCal.get(Calendar.WEEK_OF_YEAR);
int endWeek = endCal.get(Calendar.WEEK_OF_YEAR);
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
// cal.setMinimalDaysInFirstWeek(7);
ArrayList<String> main = new ArrayList<String>();
while(startYear <= endYear ){
cal.set(Calendar.YEAR, startYear);
System.out.println(cal.getMinimalDaysInFirstWeek());
if(startYear == endYear){
main.addAll(getFridays(startWeek, endWeek, cal));
}
else{
main.addAll(getFridays(startWeek, 52, cal));
startWeek = 1;
}
startYear =startYear +1;
}
for(String s: main){
System.err.println(s);
}
}
public static ArrayList<String> getFridays(int startWeek, int endWeek, Calendar cal){
ArrayList<String> fridays = new ArrayList<String>();
while(startWeek <= endWeek){
cal.set(Calendar.WEEK_OF_YEAR, startWeek);
fridays.add(cal.getTime().toString());
startWeek = startWeek+1;
}
return fridays;
}
}
Now when I ran the code i noticed that Fridays of 2011 are missing. After some debugging and online browsing i figured that Calendar.WEEK_OF_YEAR is locale specific and I have to use setMinimalDaysInFirstWeek(7) to fix it.
So uncommented the related line in the above code.
From what I understood now first week of year should start from full week of year.
For example Jan 1 2010 is friday. But it should not show up in results as i configured it to treat that week begins from Jan 3rd. But Now i still see the Jan 1 as friday
I am very much confused. Can some one explain why it is happening?
These Stackoverflow articles helped me a bit:
Why dec 31 2010 returns 1 as week of year?
Understanding java.util.Calendar WEEK_OF_YEAR
Here is an easier method, using the wonderful http://www.joda.org/joda-time/ library:
String start = "01/01/2009";
String end = "12/09/2013";
DateTimeFormatter pattern = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime startDate = pattern.parseDateTime(start);
DateTime endDate = pattern.parseDateTime(end);
List<DateTime> fridays = new ArrayList<>();
while (startDate.isBefore(endDate)){
if ( startDate.getDayOfWeek() == DateTimeConstants.FRIDAY ){
fridays.add(startDate);
}
startDate = startDate.plusDays(1);
}
at the end of this, you'd have the fridays in the fridays array. Simple?
Or if you want to speed things up, once you have gotten a friday, you can switch from using days, to using weeks:
String start = "01/01/2009";
String end = "12/09/2013";
DateTimeFormatter pattern = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime startDate = pattern.parseDateTime(start);
DateTime endDate = pattern.parseDateTime(end);
List<DateTime> fridays = new ArrayList<>();
boolean reachedAFriday = false;
while (startDate.isBefore(endDate)){
if ( startDate.getDayOfWeek() == DateTimeConstants.FRIDAY ){
fridays.add(startDate);
reachedAFriday = true;
}
if ( reachedAFriday ){
startDate = startDate.plusWeeks(1);
} else {
startDate = startDate.plusDays(1);
}
}
First off, I would not bother with weeks. Set the Calendar to the beginning of the range, and figure out which DOW it is, then increment to get to the next Friday, then simply loop adding 7 days until you are at the end of the range.
Actually, since you are always only going forward, should be something like:
int daysToAdd = FridayDOW - currentDOW;
if (daysToAdd < 0) daysToAdd += 7;
Date startDate = currentDate.add(Calendar.DAYS, daysToAdd);
Yeah, like that.
Ok, actually, for kicks, here it is in Java 8:
#Test
public void canFindAllFridaysInRange(){
start = LocalDate.of(2013, 5, 10);
end = LocalDate.of(2013, 8,30);
DayOfWeek dowOfStart = start.getDayOfWeek();
int difference = DayOfWeek.FRIDAY.getValue() - dowOfStart.getValue();
if (difference < 0) difference += 7;
List<LocalDate> fridaysInRange = new ArrayList<LocalDate>();
LocalDate currentFriday = start.plusDays(difference);
do {
fridaysInRange.add(currentFriday);
currentFriday = currentFriday.plusDays(7);
} while (currentFriday.isBefore(end));
System.out.println("Fridays in range: " + fridaysInRange);
}
Got to love the new date classes!! Of course a lambda would condense this further.
tl;dr
someLocalDate.with( // Date-only value without time-of-day and without time zone, represented by `LocalDate` class.
TemporalAdjusters.nextOrSame ( DayOfWeek.FRIDAY ) ) // Moving from one `LocalDate` object to another, to find the next Friday unless the starting date is already a Friday.
) // Return a `LocalDate` object.
java.time
The other Answers are outdated. The old java.util.Date/.Calendar classes have been supplanted in Java 8 and later by the new java.time framework. Joda-Time library is excellent, continues to be maintained, and even inspired java.time. But the Joda-Time team recommends moving on to java.time as soon as is convenient.
LocalDate
The java.time classes include LocalDate for a date-only value without time-of-day nor time zone. See Tutorial.
First parse your input strings to get LocalDate objects.
String inputStart = "01/01/2009";
String inputStop = "12/09/2013"; // 258 Fridays.
// String inputStop = "01/01/2009"; // 0 Friday.
// String inputStop = "01/02/2009"; // 1 Friday.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "MM/dd/yyyy" );
LocalDate start = LocalDate.parse ( inputStart , formatter );
LocalDate stop = LocalDate.parse ( inputStop , formatter );
In your own code, try-catch for exception in case of bad inputs. And verify that stop is indeed the same or later than start.
TemporalAdjusters
The java.time framework includes the TemporalAdjuster interface as a way of shifting date-time values. For example, getting the next or same Friday for any particular date. On your starting date, call with(TemporalAdjuster adjuster) and pass a pre-defined implementation of a TemporalAdjuster from the class TemporalAdjusters (note the plural s). See Tutorial.
List<LocalDate> fridays = new ArrayList<> (); // Collect each Friday found.
LocalDate nextOrSameFriday = start.with ( TemporalAdjusters.nextOrSame ( DayOfWeek.FRIDAY ) );
// Loop while we have a friday in hand (non-null) AND that friday is not after our stop date (isBefore or isEqual the stop date).
while ( ( null != nextOrSameFriday ) & ( ! nextOrSameFriday.isAfter ( stop ) ) ) {
fridays.add ( nextOrSameFriday ); // Remember this friday.
nextOrSameFriday = nextOrSameFriday.plusWeeks ( 1 ); // Move to the next Friday, setting up for next iteration of this loop.
}
Dump to console.
System.out.println ( "From: " + start + " to: " + stop + " are " + fridays.size () + " Fridays: " + fridays );
From: 2009-01-01 to: 2013-12-09 are 258 Fridays: [2009-01-02, 2009-01-09, 2009-01-16, 2009-01-23, 2009-01-30, 2009-02-06, 2009-02-13, 2009-02-20, 2009-02-27, 2009-03-06, 2009-03-13, 2009-03-20, 2009-03-27, 2009-04-03, 2009-04-10, 2009-04-17, 2009-04-24, 2009-05-01, 2009-05-08, 2009-05-15, 2009-05-22, 2009-05-29, 2009-06-05, 2009-06-12, 2009-06-19, 2009-06-26, 2009-07-03, 2009-07-10, 2009-07-17, 2009-07-24, 2009-07-31, 2009-08-07, 2009-08-14, 2009-08-21, 2009-08-28, 2009-09-04, 2009-09-11, 2009-09-18, 2009-09-25, 2009-10-02, 2009-10-09, 2009-10-16, 2009-10-23, 2009-10-30, 2009-11-06, 2009-11-13, 2009-11-20, 2009-11-27, 2009-12-04, 2009-12-11, 2009-12-18, 2009-12-25, 2010-01-01, 2010-01-08, 2010-01-15, 2010-01-22, 2010-01-29, 2010-02-05, 2010-02-12, 2010-02-19, 2010-02-26, 2010-03-05, 2010-03-12, 2010-03-19, 2010-03-26, 2010-04-02, 2010-04-09, 2010-04-16, 2010-04-23, 2010-04-30, 2010-05-07, 2010-05-14, 2010-05-21, 2010-05-28, 2010-06-04, 2010-06-11, 2010-06-18, 2010-06-25, 2010-07-02, 2010-07-09, 2010-07-16, 2010-07-23, 2010-07-30, 2010-08-06, 2010-08-13, 2010-08-20, 2010-08-27, 2010-09-03, 2010-09-10, 2010-09-17, 2010-09-24, 2010-10-01, 2010-10-08, 2010-10-15, 2010-10-22, 2010-10-29, 2010-11-05, 2010-11-12, 2010-11-19, 2010-11-26, 2010-12-03, 2010-12-10, 2010-12-17, 2010-12-24, 2010-12-31, 2011-01-07, 2011-01-14, 2011-01-21, 2011-01-28, 2011-02-04, 2011-02-11, 2011-02-18, 2011-02-25, 2011-03-04, 2011-03-11, 2011-03-18, 2011-03-25, 2011-04-01, 2011-04-08, 2011-04-15, 2011-04-22, 2011-04-29, 2011-05-06, 2011-05-13, 2011-05-20, 2011-05-27, 2011-06-03, 2011-06-10, 2011-06-17, 2011-06-24, 2011-07-01, 2011-07-08, 2011-07-15, 2011-07-22, 2011-07-29, 2011-08-05, 2011-08-12, 2011-08-19, 2011-08-26, 2011-09-02, 2011-09-09, 2011-09-16, 2011-09-23, 2011-09-30, 2011-10-07, 2011-10-14, 2011-10-21, 2011-10-28, 2011-11-04, 2011-11-11, 2011-11-18, 2011-11-25, 2011-12-02, 2011-12-09, 2011-12-16, 2011-12-23, 2011-12-30, 2012-01-06, 2012-01-13, 2012-01-20, 2012-01-27, 2012-02-03, 2012-02-10, 2012-02-17, 2012-02-24, 2012-03-02, 2012-03-09, 2012-03-16, 2012-03-23, 2012-03-30, 2012-04-06, 2012-04-13, 2012-04-20, 2012-04-27, 2012-05-04, 2012-05-11, 2012-05-18, 2012-05-25, 2012-06-01, 2012-06-08, 2012-06-15, 2012-06-22, 2012-06-29, 2012-07-06, 2012-07-13, 2012-07-20, 2012-07-27, 2012-08-03, 2012-08-10, 2012-08-17, 2012-08-24, 2012-08-31, 2012-09-07, 2012-09-14, 2012-09-21, 2012-09-28, 2012-10-05, 2012-10-12, 2012-10-19, 2012-10-26, 2012-11-02, 2012-11-09, 2012-11-16, 2012-11-23, 2012-11-30, 2012-12-07, 2012-12-14, 2012-12-21, 2012-12-28, 2013-01-04, 2013-01-11, 2013-01-18, 2013-01-25, 2013-02-01, 2013-02-08, 2013-02-15, 2013-02-22, 2013-03-01, 2013-03-08, 2013-03-15, 2013-03-22, 2013-03-29, 2013-04-05, 2013-04-12, 2013-04-19, 2013-04-26, 2013-05-03, 2013-05-10, 2013-05-17, 2013-05-24, 2013-05-31, 2013-06-07, 2013-06-14, 2013-06-21, 2013-06-28, 2013-07-05, 2013-07-12, 2013-07-19, 2013-07-26, 2013-08-02, 2013-08-09, 2013-08-16, 2013-08-23, 2013-08-30, 2013-09-06, 2013-09-13, 2013-09-20, 2013-09-27, 2013-10-04, 2013-10-11, 2013-10-18, 2013-10-25, 2013-11-01, 2013-11-08, 2013-11-15, 2013-11-22, 2013-11-29, 2013-12-06]
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
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
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, 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.
This code will print all dates having Friday.
public class Friday {
public static void main(String[] args) throws ParseException {
String start = "01/01/2013";
String end = "12/01/2013";
SimpleDateFormat dateFormat=new SimpleDateFormat("dd/MM/yyyy");
Calendar scal=Calendar.getInstance();
scal.setTime(dateFormat.parse(start));
Calendar ecal=Calendar.getInstance();
ecal.setTime(dateFormat.parse(end));
ArrayList<Date> fridayDates=new ArrayList<>();
while(!scal.equals(ecal)){
scal.add(Calendar.DATE, 1);
if(scal.get(Calendar.DAY_OF_WEEK)==Calendar.FRIDAY){
fridayDates.add(scal.getTime());
}
}
System.out.println(fridayDates);
}
}
Here a solution based on new stream-features of Java-8 and using my library Time4J (v4.18 or later):
String start = "01/01/2009";
String end = "12/09/2013";
ChronoFormatter<PlainDate> f =
ChronoFormatter.ofDatePattern("dd/MM/yyyy", PatternType.CLDR, Locale.ROOT);
PlainDate startDate =
f.parse(start).with(PlainDate.DAY_OF_WEEK.setToNextOrSame(Weekday.FRIDAY));
PlainDate endDate = f.parse(end);
Stream<PlainDate> fridays =
DateInterval.stream(Duration.of(1, CalendarUnit.WEEKS), startDate, endDate);
fridays.forEachOrdered(System.out::println);
// output
2009-01-02
2009-01-09
...
2013-08-30
2013-09-06
// other example: list of fridays in ISO-8601-format
List<String> result =
DateInterval.between(startDate, endDate)
.stream(Duration.of(1, CalendarUnit.WEEKS))
.map((date) -> date.toString()) // or maybe use dd/MM/yyyy => f.format(date)
.collect(Collectors.toList());
By the way, Java-9 will offer a similar solution (but with exclusive end date boundary), see also this enhancement-issue.
with Lamma Date :
List<Date> fridays = Dates.from(2015, 12, 1).to(2016, 1, 1).byWeek().on(DayOfWeek.FRIDAY).build();
for (Date friday: fridays) {
System.out.println(friday);
}
public static List<Date> getWeekNumberList(Date currentMonthDate) {
List<Date> dates = new ArrayList<>(10);
Calendar startCalendar = Calendar.getInstance();
startCalendar.setTime(currentMonthDate);
startCalendar.set(Calendar.DAY_OF_MONTH,
startCalendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(currentMonthDate);
endCalendar.set(Calendar.DAY_OF_MONTH,
endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date enddate = endCalendar.getTime();
while (startCalendar.getTime().before(enddate)) {
if (startCalendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
Date result = startCalendar.getTime();
dates.add(result);
startCalendar.add(Calendar.WEEK_OF_MONTH, 1);
} else {
startCalendar.add(Calendar.DAY_OF_MONTH, 1);
}
}
return dates;
}
Using Java 8+
LocalDate s= LocalDate.now();
LocalDate e= LocalDate.now().plusMonths(5);
List<LocalDate> dates2 = s.with(TemporalAdjusters.next(DayOfWeek.FRIDAY)).datesUntil(e, Period.ofWeeks(1)).collect(Collectors.toList());
dates2.forEach(x->System.out.println(x));
How do I create a function which take current date and return month name?
I have only date its not current date it can be any date like 2013/4/12 or 23/8/8.
Like String monthName("2013/9/11");
when call this function return the month name.
This should be fine.
It depends on the format of date.
If you try with February 1, 2011
it would work, just change this string "MMMM d, yyyy" according to your needs.
Check this for all format patterns.
And also, months are 0 based, so if you want January to be 1, just return month + 1
private static int getMonth(String date) throws ParseException{
Date d = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int month = cal.get(Calendar.MONTH);
return month + 1;
}
If you want month name try this
private static String getMonth(String date) throws ParseException{
Date d = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
String monthName = new SimpleDateFormat("MMMM").format(cal.getTime());
return monthName;
}
As I said, check web page I posted for all format patterns. If you want only 3 characters of month, use "MMM" instead of "MMMM"
java.time
I am contributing the modern answer.
System.out.println(LocalDate.of(2013, Month.SEPTEMBER, 11) // Define the date
.getMonth() // Get the month
.getDisplayName( // Get the month name
TextStyle.FULL_STANDALONE, // No abbreviation
Locale.ENGLISH)); // In which language?
Output is:
September
Use LocalDate from java.time, the modern Java date and time API, for a date.
Use LocalDate.getMonth() and Month.getDisplayName() to get the month name.
Avoid Date, Calendar and SimpleDateFormat used in the old answers from 2013. Those classes are poorly designed, troublesome and long outdated. The modern API is so much nicer to work with. Also avoid switch/case for this purpose since the month names are already built in, and using the library methods gives you clearer, terser and less error-prone code.
Use LocalDate
LocalDate today = LocalDate.now(ZoneId.systemDefault());
LocalDate aDate = LocalDate.of(2013, Month.SEPTEMBER, 11); // 2013/9/11
LocalDate anotherDate = LocalDate.of(2023, 8, 8); // 23/8/8
If you are getting the date as string input, parse the string using a DateTimeFormatter:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("u/M/d");
String stringInput = "2013/4/12";
LocalDate date = LocalDate.parse(stringInput, dateFormatter);
System.out.println(date);
2013-04-12
Use LocalDate.getMonth() and Month.getDisplayName()
To get the month name you first need to decide in which language you want the month name. I am taking English as an example and still using date from the previous snippet:
String monthName = date.getMonth()
.getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH);
System.out.println(monthName);
April
Java knows the month names in a wealth of languages. If you want the month name in the user’s language, pass Locale.getDefault() as the second argument to getDisplayName().
Link
Oracle tutorial: Date Time explaining how to use java.time.
Use this code -
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int month = calendar.get(Calendar.MONTH);
So now you have month number, you can use switch case to get name for that month.
If your date is in string format use this-
Date date = new SimpleDateFormat("yyyy-MM-dd").format(d)
Simple solution to get current month by name:
SimpleDateFormat formatterMonth = new SimpleDateFormat("MMMM");
String currentMonth = formatterMonth.format(new Date(System.currentTimeMillis()));
Function to get any month by name using format 2013/9/11: (not tested)
private String monthName(String dateToCheck){
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
date = formatter.parse(dateToCheck);
SimpleDateFormat formatterMonth = new SimpleDateFormat("MMMM");
return formatterMonth.format(new Date(date.getTime()));
}
I am using a function like this:
public String getDate(String startDate) throws ParseException {
#SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = null;
try {
d = sdf.parse(startDate);
sdf.applyPattern("MMMM dd, YYYY"); //this gives output as=> "Month date, year"
} catch (Exception e) {
Log.d("Exception", e.getLocalizedMessage());
}
return sdf.format(d);
}
You can obtain the "number" of the month as described in the other answer and then you could simply use a switch to obtain a name.
Example:
switch(month) {
case 0:
your name is January
break;
...
}
P.S. I think months are zero-based but I'm not 100% sure...