I am trying to get dates between given two dates and days, for example
date range 20/04/2014 - 210/05/2015
between these dates I am supposed to print dates between Monday to Friday for example. here is the code I developed:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date startDate = (Date) formatter.parse("20/04/2014");
Date endDate = (Date) formatter.parse("10/05/2014");
Calendar cal = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
cal.setTime(startDate);
cal1.setTime(endDate);
while (!cal.equals(cal1)) {
cal.add(Calendar.DATE, 1);
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY|| cal1.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
System.out.println(formatter.format(cal.getTime()));
System.out.println(formatter.format(cal1.getTime()));
}
//System.out.println(formatter.format(cal.getTime()));
}
What I am supposed to see is:
21/04/2014(Monday)
22/04/2014(Tuesday)
23/04/2014(Wednesday)
24/04/2014(Thursday)
25/04/2014(Friday)
28/04/2014(Monday)
29/04/2014(Tuesday)
30/04/2014(Wednesday)
01/05/2014(Thursday)
02/05/2014(Friday)
05/05/2014(Monday)
06/05/2014(Tuesday)
07/05/2014(Wednesday)
08/05/2014(Thursday)
09/05/2014(Friday)
but what I am getting is:
21/04/2014
20/05/2014
28/04/2014
20/05/2014
05/05/2014
20/05/2014
12/05/2014
20/05/2014
19/05/2014
20/05/2014
A few issues
You're reusing the same DateFormat uses to parse the input data String which is missing the required day (E) pattern. Create a separate SimpleDateFormat with pattern dd/MM/yyyy (EEEE) to display the output.
There is only output if the day is Monday or Friday, whereas there should only be output for a weekend day.
Displaying the output for variable cal1 is unnecessary
Example:
while (!calendar1.equals(calendar2)) {
calendar1.add(Calendar.DATE, 1);
if (!(calendar1.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) &&
!calendar2.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)) {
System.out.println(outputFormatter.format(calendar1.getTime()));
}
}
You can use EEEE to print day name..
formatter = new SimpleDateFormat("dd/MM/yyyy(EEEE)");
System.out.println(formatter.format(cal.getTime()));
Related
I am using SimpleDateFormat to get the current month but i want to show a recyclerview table with information of this month and past three months.
My php json loads this but i want to put automatically it in android.
periodo1 = findViewById(R.id.tittle_periodo1);
periodo2 = findViewById(R.id.tittle_periodo2);
periodo3 = findViewById(R.id.tittle_periodo3);
periodo4 = findViewById(R.id.tittle_periodo4);
SimpleDateFormat month_date = new SimpleDateFormat("yyyyMM");
String month1 = month_date.format(c.getTime());
periodo1.setText(month1);
try this :
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.MONTH, -3); // -3 is Number of months past (july)
Date newDate = calendar.getTime();
and you can format it if you want :
String date = DateFormat.format("MM/dd/yyyy", newDate).toString();
With Java8 syntax you can use time library to achieve this
import java.time.LocalDate;
LocalDate now = LocalDate.now(); // 2019-11-01 (Nov)
LocalDate minusOneMonth = now.minusMonths(1); // 2019-10-01
minusOneMonth.getMonth().getValue(); // Gives -1 month (10)
LocalDate minusTwoMonth = now.minusMonths(2); // 2019-09-01
minusTwoMonth.getMonth().getValue(); // Gives -2 month (09)
Hope that's what you are looking for.
If you can't use Java8 syntax, use following
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.MONTH, -1);
Date newDate = cal.getTime();
.... = new SimpleDateFormat("M")
I went to display the current date and the six (6) last dates
example :
02/11/2012
01/11/2012
31/10/2012
30/10/2012
29/10/2012
28/10/2012
to get the current day in JAVA I used :
Date date = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
System.out.println("current day : "+sdf.format(date));
but how do I decrement the days ?
You can use the Calendar#add method to substract a day, like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
System.out.println(sdf.format(date)); //remove line to display only the last 5 days
for (int i=0;i<5;i++){
cal.add(Calendar.DAY_OF_MONTH,-1);
date=cal.getTime();
System.out.println(sdf.format(date));
}
Like Jon Skeet (soon Mr. 500k :) ) suggested, I too find the Joda Time API more cleaner and appropriate, even for such simple tasks:
DateTime dt = new DateTime();
for (int i = 0; i < 6; i++) {
System.out.println(dt.toString("yyyy/MM/dd"));
dt = dt.minusDays(1);
}
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
System.out.println("current day : "+sdf.format(c.getTime()));
// decrement 1 day
c.add(Calendar.DAY_OF_MONTH, -1);
// getTime() returns a java.util.Date
System.out.println("the day before : "+sdf.format(c.getTime()));
// getTimeInMillis() returns a long, which can be used to construct a java.sql.Date
System.out.println("the day before : "+sdf.format(new java.sql.Date(c.getTimeInMillis()));
And so on...
How do I find out the last month and its year in Java?
e.g. If today is Oct. 10 2012, the result should be Month = 9 and Year = 2012. If today is Jan. 10 2013, the result should be Month = 12 and Year = 2012.
Your solution is here but instead of addition you need to use subtraction
c.add(Calendar.MONTH, -1);
Then you can call getter on the Calendar to acquire proper fields
int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year = c.get(Calendar.YEAR);
java.time
Using java.time framework built into Java 8:
import java.time.LocalDate;
LocalDate now = LocalDate.now(); // 2015-11-24
LocalDate earlier = now.minusMonths(1); // 2015-10-24
earlier.getMonth(); // java.time.Month = OCTOBER
earlier.getMonth.getValue(); // 10
earlier.getYear(); // 2015
Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.
DateTime#minusMonths method would help you get previous month.
DateTime month = new DateTime().minusMonths (1);
you can use the Calendar class to do so:
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println(format.format(cal.getTime()));
This prints : 2012.09.10 11:01 for actual date 2012.10.10 11:01
The simplest & least error prone approach is... Use Calendar's roll() method. Like this:
c.roll(Calendar.MONTH, false);
the roll method takes a boolean, which basically means roll the month up(true) or down(false)?
YearMonth class
You can use the java.time.YearMonth class, and its minusMonths method.
YearMonth lastMonth = YearMonth.now().minusMonths(1);
Calling toString gives you output in standard ISO 8601 format: yyyy-mm
You can access the parts, the year and the month. You may choose to use the Month enum object, or a mere int value 1-12 for the month.
int year = lastMonth.getYear() ;
int month = lastMonth.getMonthValue() ;
Month monthEnum = lastMonth.getMonth() ;
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}
You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0
Calendar c = Calendar.getInstance();
c.set(2011, 2, 1);
c.add(Calendar.MONTH, -1);
int month = c.get(Calendar.MONTH) + 1;
assertEquals(1, month);
You get by using the LocalDate class.
For Example:
To get last month date:
LocalDate.now().minusMonths(1);
To get starting date of last month
LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
Similarly for Year:
To get last year date:
LocalDate.now().minusYears(1);
To get starting date of last year :
LocalDate.now().minusYears(1).with(TemporalAdjusters.lastDayOfYear());
Here's the code snippet.I think it works.
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleMonth=new SimpleDateFormat("MMMM YYYY");
cal.add(Calendar.MONTH, -1);
System.out.println(simpleMonth.format(prevcal.getTime()));
I have a string (Jan12) (generated by applying some operations on current date {20-jan-2012}) Now i want to convert back this string into Date format . Also the value should be same i.e the new Date object should have value jan12 and not (20-jan-2012) . Pls help . I have tried doing
java.sql.Date.valueOf("Jan12") [this throws IllegalArgumentException]
and also
new SimpleDateFormat("MMMyy").parse("Jan12") [By this Date gets converted to 20-jan-2012]
Output required : A Date Object having value Jan12 (12 is the year)
My Code : new java.text.SimpleDateFormat("MMMyy").format(new java.text.SimpleDateFormat("yyyy-MM-dd").parse(s)) // It is a string which gives Jan12
Now i really want to convert Mycode into a Date object
Date now = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s1 = df.format(now);
System.out.println(s1); // 2012-01-20
java.sql.Date d111=java.sql.Date.valueOf(s1);
System.out.println(d111); // 2012-01-20
DateFormat df1 = new SimpleDateFormat("MMMyy");
String s2 = df1.format(d111);
System.out.println(s2); //Jan12
Now i want s2 to be converted in Date object
#Aditya,
If you use the Str2 which gives "Jan12", there is no date part in that string and therefore if you convert it to a date object, it will get "Jan" as month, 12 as year but it cant find "day" in that String.
if you use below code
try
{
Date d2 = df1.parse(s2); //here s2 is your string which gives "JAN12"
System.out.println(d2);
}
catch(ParseException pe)
{
System.out.println("parse exception..");
}
The output to the above code will be:
Sun Jan 01 00:00:00 IST 2012
notice here that day part is reset to the first day of the month
Therefore, it is not possible to get a complete date object as your original Date, the month and year are preserved, but the day part is lost.
What do you mean "gets converted"? How your Date is displayed is a separate issue. Look into formatting a Date.
So the 12 is day, not a year - you should parse it as such. Aslo, you'll need to tell it what year this is:
System.out.println(new SimpleDateFormat("yyyyMMMdd").parse("2012" + "Jan12"));
Output
Thu Jan 12 00:00:00 EST 2012
Use the SimpleDateFormat class properly, it will do exactly what you want
String str_date="12-Jan-2012";
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse(str_date);
Note: the formatter.parse() method throws ParseException, catch it;
If 12 is a year
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("MMMyy").parse("Jan12"));
calendar.set(Calendar.DATE, 1);
Date date = calendar.getTime(); // First Jan 2012
If 12 is a day
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("MMMdd").parse("Jan12"));
calendar.set(Calendar.YEAR, 2012);
Date date = calendar.getTime(); // 12 Jan 2012
I understand that you want to format your Date object into a String representation.
You can use SimpleDateFormat for this, analog to your second example:
Date d = new Date(112, 0, 20); //don't construct a date like this in production code, use a Calendar instance instead
String formattedDate = new SimpleDateFormat("MMMyy").format(d); // -> "Jan12"
Note that your Date object represents a specific point in time, it will always have a day and a time associated with it.
If you want to compare Dates with the resolution of a month, you have to set day and time to neutral values:
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
d = cal.getTime();
Just extend Date and customize it to use your favourite parse & format methods.
There are two date variables (Date1 and Date2) in the format YYYYMMDD. What i want is, according to the Date1 I want to set Date2 to the next month day one. For example :
If Date1 = 20111120 then
I want to set Date2 to 20111201
If Date1 = 20111210 then
The Date2 should be set to 20120101
No matter the Date1 the Date2 has to be set to next month day one. I cant figure this out how to do it.
Could anyone please help me on this issue.
use Calendar to move to the first of next month , SimpleDateFormat to parse from String to Date
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, 1);
DateFormat format = new SimpleDateFormat("yyyyMMdd");
Calendar calendar = Calendar.getInstance();
String date1 = "20111120";
calendar.setTime(format.parse(date1));
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, 1);
String date2 = format.format(calendar.getTime()); // date2 is "20111201"
Some caveats:
if you call this more than once, it might be a good idea to instantiate format and calendar only once.
SimpleDateFormat is not thread safe, so make sure to instantiate one SimpleDateFormat object for each threads (eg. using ThreadLocal)