Find the remaining months in a year - java

I am trying to find a way to get an array of month for a year(Ex:2017)
The array to be the remaining months in a year only
Is this possible, What is the best way to achieve this
I searched for the answer couldn't find it
ex:{"October","November","December"}
What I have done so far: I am able to get current year
Date now = new Date();
int year = now.getYear();

You should better use new API LocalDate rather than Date, it's easier to use
first, you need to get the current date : here it's 07/10/201
you need to find out many month there is until the end of the year : here it's 2
then you create an array of the size + 1 (+1 is for current month) : here size is 3
then you fill the array with the month of date you have + i month
LocalDate date = LocalDate.now();
int nbMonthRemain = 12 - date.getMonth().getValue();
String[] monthsRemaining = new String[nbMonthRemain + 1];
for (int i = 0; i < monthsRemaining.length; i++) {
monthsRemaining[i] = date.plusMonths(i).getMonth().toString();
}
System.out.println(Arrays.toString(monthsRemaining)); // [OCTOBER, NOVEMBER, DECEMBER]
Tips :
Replace .toString() by :
.getDisplayName(TextStyle.FULL, Locale.ENGLISH); to get [October, November, December]
.getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH); to get [10, 11, 12]
.getDisplayName(TextStyle.SHORT, Locale.ENGLISH); to get [Oct, Nov, Dec]
...

Use GregorianCalendar.getInstance().get(Calendar.MONTH) to get current month number (For oct you will get 9)

i believe something like below code could help
import java.text.DateFormatSymbols;
import java.util.List;
import java.util.ArrayList;
public List GetLeftMonth(Integer Mon_num){
List<String> monthsList = new ArrayList<String>();
String[] months = new DateFormatSymbols().getMonths();
for (int i = Mon_num; i < months.length; i++) {
String month = months[i];
System.out.println("month = " + month);
monthsList .add(months[i]);
}
return monthsList;
}

public static void main(String[] args) {
LocalDate now = LocalDate.now();
int currentMonth = now.getMonthValue();
int monthsInAYear = 12;
int monthsRemaining = monthsInAYear - currentMonth;
System.out.println(monthsRemaining); // 2
for (int i = currentMonth; i <= monthsInAYear; i++) {
System.out.println(getMonthName(i)); // OCTOBER NOVEMBER DECEMBER
}
}
private static Month getMonthName(int monthValue) {
return Month.of(monthValue);
}
Don't forget to import import java.time.LocalDate;
import java.time.Month;
As already said, don't use java.util.Date but java.time.LocalDate instead, since it is (arguably) easier to work with.

Related

How to get list of passed months of this year java?

I am using SingleLine chart from PhilJay/MPAndroidChart android library and i need a list of passed months of current year. So for example from Jan to Oct, but when is October pass then from Jan to Nov and so on.
I tried these: Getting List of Month for Past 1 year in Android dynamically,
and Calculate previous 12 months from given month - SimpleDateFormat
but all of these are for previosly 12 months and i want from start of current year
#SuppressLint("SimpleDateFormat")
private void handleXAxis() {
List<String> allDates = new ArrayList<>();
String maxDate = "Jan";
SimpleDateFormat monthDate = new SimpleDateFormat("MMM");
Calendar cal = Calendar.getInstance();
try {
cal.setTime(Objects.requireNonNull(monthDate.parse(maxDate)));
} catch (ParseException e) {
e.printStackTrace();
}
for (int i = 1; i <= 12; i++) {
String month_name1 = monthDate.format(cal.getTime());
allDates.add(month_name1);
cal.add(Calendar.MONTH, -1);
}
}
tl;dr ⇒ java.time
Months until (including) the current one as List<YearMonth>:
public static List<YearMonth> getMonthsOfCurrentYear() {
YearMonth currentMonth = YearMonth.now();
List<YearMonth> yearMonths = new ArrayList<>();
for (int month = 1; month <= currentMonth.getMonthValue(); month++) {
yearMonths.add(YearMonth.of(currentMonth.getYear(), month));
}
return yearMonths;
}
Months until (including) the current one as List<String>:
public static List<String> getMonthNamesOfCurrentYear() {
YearMonth currentMonth = YearMonth.now();
List<String> yearMonths = new ArrayList<>();
for (int month = 1; month <= currentMonth.getMonthValue(); month++) {
yearMonths.add(YearMonth.of(currentMonth.getYear(), month)
.format(DateTimeFormatter.ofPattern("MMM",
Locale.ENGLISH)));
}
return yearMonths;
}
as an alternative, you can use the display name of the Month instead of using a DateTimeFormatter.ofPattern("MMM")
public static List<String> getMonthNamesOfCurrentYear() {
YearMonth currentMonth = YearMonth.now();
List<String> yearMonths = new ArrayList<>();
for (int month = 1; month <= currentMonth.getMonthValue(); month++) {
yearMonths.add(Month.of(month)
.getDisplayName(TextStyle.SHORT, Locale.ENGLISH));
}
return yearMonths;
}
The output of the second and third example:
Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct
when invoked like
System.out.println(String.join(", ", getMonthNamesOfCurrentYear()));

How to display all Mondays between two dates?

Im trying display all Mondays between two dates but I have no idea how to do it. I want ask user to input two dates using Scanner, to output all Mondays.
String s = "2020-07-20";
String e = "2020-09-20";
LocalDate start = LocalDate.parse(s);
LocalDate end = LocalDate.parse(e);
List<LocalDate> totalDates = new ArrayList<>();
while (!start.isAfter(end)) {
totalDates.add(start);
start = start.plusDays(1);
}
To get the the first Monday, use:
LocalDate monday = start.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
Now you have to deal with an edge case: What if there is no Monday between start and end? That would mean that the Monday computed here is after end:
if (monday.isAfter(end)) {
totalDates = List.of();
}
After that, you can get a sequence of Mondays with the convenient datesUntil method:
totalDates = monday.datesUntil(end, Period.ofWeeks(1)).collect(Collectors.toList());
Note that datesUntil does not include the end date. If you need the end date included, pass in end.plusDays(1).
You need to use getDayOfWeek(), here is the solution:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class AllMondays {
public static void main(String[] args) {
String s = "2020-07-20";
String e = "2020-09-20";
LocalDate start = LocalDate.parse(s);
LocalDate end = LocalDate.parse(e);
List<LocalDate> totalDates = new ArrayList<>();
LocalDate nextMonday = start;
int daysToAdvance = 1;
while (!nextMonday.isAfter(end)) {
if (nextMonday.getDayOfWeek() == DayOfWeek.MONDAY) {
daysToAdvance = 7;
totalDates.add(nextMonday);
}
nextMonday = nextMonday.plusDays(daysToAdvance);
}
System.out.println(totalDates);
}
}
You can use .getDayOfWeek() to get DayOfWeek and compare with DayOfWeek.MONDAY
while (!start.isAfter(end)) {
if(start.getDayOfWeek().equals(DayOfWeek.MONDAY)) {
totalDates.add(start);
}
start = start.plusDays(1);
}
And optimization is use start.plusWeeks(1) instead of start.plusDays(1) and you need to get the next monday before.
start = start.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
while (!start.isAfter(end)) {
if(start.getDayOfWeek().equals(DayOfWeek.MONDAY)) {
totalDates.add(start);
}
start = start.plusWeeks(1);
}
Here "find_day" is the day you want to find in date range
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
Date sub_start_date = format1.parse("01-06-2021");
Date enddate = format1.parse("30-06-2021");
Calendar min_date_c = Calendar.getInstance();
min_date_c.setTime(sub_start_date);
Calendar max_date_c = Calendar.getInstance();
max_date_c.setTime(enddate);
for (Calendar loopdate = min_date_c; min_date_c.before(max_date_c); min_date_c.add(Calendar.DATE, 1), loopdate = min_date_c) {
int dayOfWeek = loopdate.get(Calendar.DAY_OF_WEEK);
// if (dayOfWeek == Calendar.MONDAY || dayOfWeek == Calendar.SATURDAY) {
if (dayOfWeek == find_day) {
Calendar[] disabledDays = new Calendar[1];
disabledDays[0] = loopdate;
Date newdate = loopdate.getTime();
String strDate = format1.format(newdate);
Log.e("DATES>>> ", "" + strDate);
}
}

Best way to find and return a String of next day's date? [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 7 years ago.
I used a basic technique to implement a method that finds the date of the next day based on the given parameter in the format YYYY-MM-DD and returns the next day in the same format.
Can you please take a look at the code and tell me if it is inefficient or not? It works perfectly fine, but I would prefer to implement a method with more efficiency and fewer lines of code if possible. Keep in mind that any values of the month or day that are single digits numbers have to be formatted with a 0 in the tens place.
public String nextDate(String date){ //ex: 2016-01-31 -returns-> 2016-02-01
int MMrange = 30;
String result = "";
String daystr = date.substring(8,10);
String monthstr = date.substring(5,7);
int day = Integer.parseInt(daystr);
int month = Integer.parseInt(monthstr);
int year = Integer.parseInt(date.substring(0,4));
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) MMrange = 31;
else if(month==2) MMrange = 28;
if(year%4==0&&month==2) MMrange = 29;
if(day==MMrange){
day =1;
month++;
}else if(month==12&&day==31){
year++;
month = 1;
day = 1;
}else{
day++;
}
result = Integer.toString(year)+"-"+Integer.toString(month)+"-"+Integer.toString(day);
if(month <=9&&day<=9) result = Integer.toString(year)+"-0"+Integer.toString(month)+"-0"+Integer.toString(day);
else if(month <= 9) result = Integer.toString(year)+"-0"+Integer.toString(month)+"-"+Integer.toString(day);
else if(day <= 9) result = Integer.toString(year)+"-"+Integer.toString(month)+"-0"+Integer.toString(day);
return result;
}
Try this...
Updated
// imports...
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public static String getNextdt(String dt) {
try {
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
final Date date = format.parse(dt);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, 1);
System.out.println(format.format(calendar.getTime()));
return format.format(calendar.getTime());
} catch (Exception e) {
}
}
You should use a java.text.DateFormat for format and a java.util.Calendar for calculation like
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 1);
return df.format(cal.getTime());
A shorter way, provided that you use Java 8 is:
LocalDate localDate = LocalDate.now();
localDate.plusDays(1);
System.out.println(localDate.toString());
Hope this works for you.

How to print next day using java

i have a method which has to print the next seven days but instead of printing next seven days it prints last seven days,
could some one help me fixing this please
here is the method i use,
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class TestCalandar
{
public static void main(String[] args)
{
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE");
String date[] = null;
date = df.format(new Date()).split("/");
Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(date[2]), Integer.parseInt(date[0]) - 1, Integer.parseInt(date[1]));
Map<String, String> currentWeekMap = new HashMap<String, String>();
for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++)
{
cal.set(Calendar.DAY_OF_WEEK, i);
currentWeekMap.put(dayFormat.format(cal.getTime()), df.format(cal.getTime()));
}
System.out.println(currentWeekMap);
}
}
Use the new Java8 time API. This will accomplish what your code was trying to.
Map<String, String> currentWeekMap = new HashMap<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate today = LocalDate.now();
for (int i=1; i<=7; i++) {
LocalDate newDay = today.plusDays(i);
String dayOfWeek = newDay.getDayOfWeek().toString();
String formattedDate = newDay.format(formatter);
currentWeekMap.put(dayOfWeek, formattedDate);
}
System.out.println(currentWeekMap);
I really short example
public class DateUtils {
private DateUtils() {}
public static Date addDays(Date baseDate, int daysToAdd) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(baseDate);
calendar.add(Calendar.DAY_OF_YEAR, daysToAdd);
return calendar.getTime();
}
}
Here's the solution which should output what you want :). Hope it helps!
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
class TestCalandar
{
public static void main(String[] args){
Calendar now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
String[] days = new String[7];
int delta = now.get(Calendar.DAY_OF_WEEK)-6;
now.add(Calendar.DAY_OF_MONTH, delta );
for (int i = 0; i < 7; i++)
{
days[i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH, 1);
}
for(int i = 0 ; i < days.length ; i++){
System.out.println(days[i]);
}
}
}
The method Calendar.set sets the specified field, in this case the DAY_OF_WEEK field, to the specified value. The effect on the other fields is dependent on other factors, more specifically, the effect of Calendar.set is to change the day of week and the adjustment will happen within the current WEEK_OF_YEAR. This behavior is dependent on the locale that the code is running in.
Instead you, need to add a day, so you could use the Calendar.add method.
cal.set(Calendar.DAY_OF_WEEK, i)
could change to:
cal.add(Calendar.DAY_OF_YEAR, 1);
which will add one day to the day for every iteration of the loop.
If the output is required to be printed in order, then printing on each iteration of the loop would be better than putting into the HashMap, as HashMaps are not ordered.
Also, you state that your requirement is to print the next 7 days, so the first day should be tomorrow, which would mean that you can remove the following line. When you call Calendar.getInstance(), the date is automatically set to the current time in the current time zone, so you just want to start adding to the calendar from right now, which means the first date will be tomorrow.
cal.set(Integer.parseInt(date[2]), Integer.parseInt(date[0]) - 1, Integer.parseInt(date[1]));
See here: http://www.tutorialspoint.com/java/util/calendar_add.htm for the first search on Calendar.add in google.
Here is the working one,
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE");
String date[] = null;
date = df.format(new Date()).split("/");
Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(date[2]), Integer.parseInt(date[0]), Integer.parseInt(date[1]));
Map<String, String> currentWeekMap = new HashMap<String, String>();
for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) {
cal.add(Calendar.DATE, 1);
currentWeekMap.put(dayFormat.format(cal.getTime()), df.format(cal.getTime()));
}
System.out.println(currentWeekMap);
}

find days difference between 2 dates and how many days in each month

I could use some help with this method I'm trying to make. I have a Problem Object, which has a target date and i need to find out how many days this problem is late divided/split by months, compared to today's date.
Image this situation:
Lets say that today's date is 05-02-2013.
ID Target date
P1 02-02-2013
P2 27-01-2013
P3 26-01-2013
P4 05-12-2012
This means that each problem is this many days late in the following months:
DEC JAN FEB
P1 3
P2 4 5
P3 5 5
P4 26 31 5
A problem can not be older than 12 months.
Now i need a method to sum these numbers storing the month name and a summed number of late days. If the target month and now month are the same, its an easy case, because i can just substract the days and store the month, but what to do when its not the case? I have the following code:
List<Problem> problems = problemQuery.getResultList(); //Problems list is already filtered and contain only late problems.
Calendar now = Calendar.getInstance();
Calendar before = Calendar.getInstance();
Map<Integer, Integer> newMap = new TreeMap<Integer, Integer>(); //map that contains month number and daysLateCount
for (Problem p : problems) {
before.setTime(p.getTarget_date());
int nowMonth = now.get(Calendar.MONTH);
int beforeMonth = before.get(Calendar.MONTH);
if (beforeMonth == nowMonth) { //easy case when both dates have same month
int result = now.get(Calendar.DAY_OF_MONTH) - before.get(Calendar.DAY_OF_MONTH);
if (newMap.containsKey(nowMonth)) {
int newLateDaysValue = newMap.get(nowMonth)+result; //get old result and add the new
newMap.put(nowMonth, newLateDaysValue);
}
else {
newMap.put(nowMonth, result);
}
}
else {
//What to do here???
}
}
Perhaps i could even skip the if-else clause and make an algorithm that could handle both cases? I don't know please help :)
The best way is to use Joda Time library: http://www.joda.org/joda-time/
Java Date/Time API is not very good and useful for such purposes.
I think there is a relatively simple solution to this, the algorithm is as follows:
import java.util.Calendar;
public class test {
public static void main(String[] args){
Calendar today = Calendar.getInstance();
Calendar problemDate = Calendar.getInstance();
today.set(2013, 01, 05);
problemDate.set(2012, 11, 05);
System.out.println(today.getTime());
System.out.println(problemDate.getTime());
// This might need further validation to make sure today >= problemDate
int diffYear = today.get(Calendar.YEAR) - problemDate.get(Calendar.YEAR);
int differenceInMonths = diffYear * 12 + today.get(Calendar.MONTH) - problemDate.get(Calendar.MONTH);
//int differenceInMonths = today.get(Calendar.MONTH) - problemDate.get(Calendar.MONTH);
for(int i = 0; i <= differenceInMonths; i++) {
int daysDifference;
if (differenceInMonths == 0) {
daysDifference = today.get(Calendar.DAY_OF_MONTH) - problemDate.get(Calendar.DAY_OF_MONTH);
} else {
if ( i == 0) { // first month
daysDifference = problemDate.getActualMaximum(Calendar.DAY_OF_MONTH) - problemDate.get(Calendar.DAY_OF_MONTH);
}
else if( i == differenceInMonths ) { // last month
daysDifference = today.get(Calendar.DAY_OF_MONTH);
}
else {
Calendar cal= Calendar.getInstance();
cal.set(Calendar.MONTH, problemDate.get(Calendar.MONTH) + i);
daysDifference = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
}
System.out.println(daysDifference);
}
}
}
Which outputs:
Tue Feb 05 14:35:43 GMT 2013
Wed Dec 05 14:35:43 GMT 2012
26
31
5
You should be able to wrap this up into your code, and in a loop fairly easily, and also remove the print statements to insert into whatever data structure you have.
A solution using Joda-Time:
LocalDate today = new LocalDate(2013, 2, 5);
LocalDate targetDate = new LocalDate(2012, 12, 5); // example with target date P4
LocalDate begin = targetDate;
LocalDate end = begin.dayOfMonth().withMaximumValue();
while (end.isBefore(today)) {
Days days = Days.daysBetween(begin, end);
if (days.getDays() > 0) {
System.out.println(end.monthOfYear().getAsText() + ": " + days.getDays());
}
begin = end;
end = begin.plusDays(1).dayOfMonth().withMaximumValue();
}
end = today;
Days days = Days.daysBetween(begin, end);
if (days.getDays() > 0) {
System.out.println(end.monthOfYear().getAsText() + ": " + days.getDays());
}
Prints the following result for e.g. target date P4:
December: 26
January: 31
February: 5
The year is needed, if only to know how many days are in February.
for (Problem p : problems) {
int nowYear = now.get(Calendar.YEAR);
int nowMonth = now.get(Calendar.MONTH);
int nowDay = now.get(Calendar.DAY_OF_MONTH);
before.setTime(p.getTarget_date());
int beforeYear = before.get(Calendar.YEAR);
int beforeMonth = before.get(Calendar.MONTH);
int beforeDay = before.get(Calendar.DAY_OF_MONTH);
while (beforeYear < nowYear || beforeMonth < nowMonth) {
int daysInMonth =
before.getActualMaximum(Calendar.DAY_OF_MONTH);
int result = daysInMonth - beforeDay;
Integer oldLateDaysValue = newMap.get(beforeMonth);
newMap.put(beforeMonth,
oldLateDaysValue == null ?
result : (oldLateDaysValue + result));
// For all subsequent months, calculate using entire month.
beforeDay = 0;
before.add(Calendar.MONTH, 1);
beforeYear = before.get(Calendar.YEAR);
beforeMonth = before.get(Calendar.MONTH);
}
int result = nowDay - beforeDay;
Integer oldLateDaysValue = newMap.get(beforeMonth);
newMap.put(beforeMonth,
oldLateDaysValue == null ?
result : (oldLateDaysValue + result));
}
System.out.println(newMap);
}

Categories