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);
}
Related
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);
}
}
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.
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.
I am trying to get dates, which occurs in every 5 days from start date to end date.
Eg.
if start date= 11/10/2014 i.e MM/DD/YYYY format
and end date =11/26/2014
then my **expected output** is =
[11/15/2014,11/20/2014,11/25/2014]
I tried below but very confuse where to run loop for getting exact ouput. Currently from below code i am only getting 1 date in list
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class TestDate {
// mm/dd/yyyy
public List getDates(Date fromDate,int frequency,Date endDate){
List list=new ArrayList<Date>();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(fromDate); // Now use today date.
c.add(Calendar.DATE, frequency); // Adding 5 days
String newDate = sdf.format(c.getTime());
String sEndDate=sdf.format(endDate);
if((newDate.compareTo(sEndDate) < 0) || (newDate.compareTo(sEndDate) == 0)){
list.add(newDate);
}
//Weekly=7,Bi-Weekly14,Monthly-30,Semi-Monthly-15
return list;
}
public static void main(String[] args) {
try {
TestDate obj=new TestDate();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date s = sdf.parse("11/10/2014");
Date e = sdf.parse("11/26/2014");
System.out.println(obj.getDates(s, 5, e));
}
catch(Exception e) {
System.err.println("--exp in main---"+e);
}
}
}
Correct answer is below *Thanks to Almas*
public List getDates(Date fromDate,int frequency,Date e){
List list=new ArrayList<Date>();
Calendar c = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c2.setTime(e); // Now use today date.
Date endDate=c2.getTime();
Date newDate=fromDate;
while(true){
c.add(Calendar.DATE, frequency);
newDate=c.getTime();
if(newDate.compareTo(endDate)<=0){
list.add(newDate);
}else{
break;
}
}
//Weekly=7,Bi-Weekly14,Monthly-30,Semi-Monthly-15
return list;
}
Why do you want date to be as string and compared lexicographically instead of comparing them as date?
String newDate = sdf.format(c.getTime());
String sEndDate=sdf.format(endDate);
This should be changed as
Date newDate = c.getTime();
Also you are using two if condition which you could do in one like below :
if (newDate.compareTo(endDate) <= 0) {
list.add(newDate);
}
as far as looping is concerned you should do it in your getDates method like below:
Date newDate;
while (true) {
c.add(Calendar.DATE, frequency); // Adding 5 days
newDate = c.getTime();
if (newDate.compareTo(endDate) <= 0) {
list.add(newDate);
} else {
break;
}
}
Make use of Apache commons DateUtils. This will make your code simple
Date tempDate = DateUtils.addDays(fromDate, frequency);
while (tempDate.before(endDate))
{
list.add(tempDate);
tempDate = DateUtils.addDays(tempDate, frequency);
}
return list;
try this one
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class NewClass1 {
// mm/dd/yyyy
public List getDates(Date fromDate, int frequency, Date endDate) {
List list = new ArrayList<Date>();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(fromDate); // Now use today date.
c.add(Calendar.DATE, frequency); // Adding 5 days
String newDate = sdf.format(c.getTime());
//System.out.println("date"+newDate);
String formDate = sdf.format(fromDate);
String sEndDate = sdf.format(endDate);
int x = 1;
while (((newDate.compareTo(sEndDate) > 0) || (newDate.compareTo(sEndDate) != 0)) && x < frequency) {
c.add(Calendar.DATE, frequency);
sEndDate = sdf.format(c.getTime());
x++;
System.out.println("date: " + sEndDate);
list.add(newDate);
}
//Weekly=7,Bi-Weekly14,Monthly-30,Semi-Monthly-15
return list;
}
public static void main(String[] args) {
try {
NewClass1 obj = new NewClass1();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date s = sdf.parse("11/10/2014");
Date e = sdf.parse("11/26/2014");
obj.getDates(s, 5, e);
} catch (Exception e) {
System.err.println("--exp in main---" + e);
}
}
}
public class CalendarCal {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat simpleDateformat = new SimpleDateFormat("yy");
String m = simpleDateformat.format(date);
System.out.println("Year:" + m);
int year = Calendar.getInstance().get(Calendar.YEAR) % 100;
System.err.println(year);
}
}
I am able to retrieve the current year from this. How can I get the last (previous) year with help of utility? I don't want to do a calculation like currentyear - 1 or like that.
Just use Calendar.add method to "add" -1 to the year and wrap it in your own utility method:
private static int getPreviousYear() {
Calendar prevYear = Calendar.getInstance();
prevYear.add(Calendar.YEAR, -1);
return prevYear.get(Calendar.YEAR);
}
Example:
public static void main(String[] args) {
System.out.println(getPreviousYear());
}
Prints on my system:
2011
import java.time.Year;
public class TryTime {
public static void main(String[] args) {
System.out.println(Year.now().minusYears(1));
}
}
It is as simple as explained below:
//Create calendar instance
Calendar instance = Calendar.getInstance();
//Set your date to it
instance.setTime(date);
//Substract one year from it
instance.add(Calendar.YEAR, -1);
//Use the pattern you wish to display the date
SimpleDateFormat isoFormat = new SimpleDateFormat("dd-MMM-yyyy");
// Convert the date to string using format method
String previousYearDate = isoFormat.format(instance.getTime());
public static String previousDateString(String dateString)
throws ParseException {
// Create a date formatter using your format string
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
// Parse the given date string into a Date object.
// Note: This can throw a ParseException.
Date myDate = dateFormat.parse(dateString);
// Use the Calendar class to subtract one day
Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -1);
// Use the date formatter to produce a formatted date string
Date previousDate = calendar.getTime();
String result = dateFormat.format(previousDate);
return result;
}
import java.util.*;
public class GetYear {
public static void main(String []arg){
Calendar cal=Calendar.getInstance();
int year=cal.get(Calendar.YEAR)-1;
System.out.println("Current Year: " + year );
}
}
Light weight solution (without direct or indirect constructor call of any Object).
final class YearUtil {
static final int MILLIS_IN_SECOND = 1000;
static final int SECONDS_IN_MINUTE = 60;
static final int MINUTES_IN_HOUR = 60;
static final int HOURS_IN_DAY = 24;
static final int DAYS_IN_YEAR = 365;
static final long MILLISECONDS_IN_YEAR = (long) MILLIS_IN_SECOND
* SECONDS_IN_MINUTE * MINUTES_IN_HOUR * HOURS_IN_DAY * DAYS_IN_YEAR;
public static int getCurrentYear() {
return (int) (1970 + System.currentTimeMillis() / MILLISECONDS_IN_YEAR);
}
}
Than use it:
int prevYear = YearUtil.getCurrentYear() - 1;
These numbers are so big that there is no need to bother about even years (in your live and your childs childs childs...) ;)
Joda-Time
Using Joda-Time 2.4:
int year = DateTime.now( DateTimeZone.forID( "Europe/Paris" ) ).minusYears( 1 ).getYear();
Calendar calendarEnd=Calendar.getInstance();
// You can substract from the current Year to get the previous year last dates.
calendarEnd.set(Calendar.YEAR,calendarEnd.get(Calendar.YEAR)-3);
calendarEnd.set(Calendar.MONTH,11);
calendarEnd.set(Calendar.DAY_OF_MONTH,31);
Date endDate=calendarEnd.getTime();
System.out.println("\nEND Date Of this year : "+endDate);