This question already has answers here:
Why is January month 0 in Java Calendar?
(18 answers)
Why Java Calendar set(int year, int month, int date) not returning correct date? [duplicate]
(3 answers)
Closed last year.
I was trying to do a question where I have to print the name of the weekday. At first, i tried using this method:
My program
public static String findDay(int month, int day, int year){
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
Date date = calendar.getTime();
System.out.println(date);
return new SimpleDateFormat("EEEE").format(date).toUpperCase();
}
In this, I am getting the output as THURSDAY.
However, when I used the below code, I am getting the correct answer that is MONDAY
class Result {
public static String findDay(int month, int day, int year) {
/*Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
Date date = calendar.getTime();
return new SimpleDateFormat("EEEE").format(date).toUpperCase();*/
String final_day = "";
String input_date = day + "/" + month + "/" + year;
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
try
{
DateFormat format2 = new SimpleDateFormat("EEEE");
final_day = format2.format(format1.parse(input_date));
}
catch(Exception e){}
return final_day.toUpperCase();
}
}
Can anyone tell me how is it possible?
In my app, I need next seven days from the current day.
I tried the following solution but it is skipping some days.
Calendar calendar = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
for (int i = 0; i < 7; i++) {
calendar.add(Calendar.DATE, i);
String day = sdf.format(calendar.getTime());
Log.i(TAG, day);
}
I am getting the following output:
Sunday 18-Oct-2015
Monday 19-Oct-2015
Wednesday 21-Oct-2015
Saturday 24-Oct-2015
Wednesday 28-Oct-2015
Monday 02-Nov-2015
Sunday 08-Nov-2015
I also tried Calendar.DAY_OF_WEEK, Calendar.DAY_OF_MONTH, Calendar.DAY_OF_YEAR instead of Calendar.DATE but getting the same output.
Try this:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
for (int i = 0; i < 7; i++) {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.DATE, i);
String day = sdf.format(calendar.getTime());
Log.i(TAG, day);
}
You have one instance of calendar and are adding 1, 2, 3, 4, 5, 6, and 7 days to it without resetting it. The above solution moves object creation to be within the loop.
found a easiest way with java 8+
plusDays
final LocalDate date = LocalDate.now();
final LocalDate plusDays = date.plusDays(7);
//if you want to show past 7 days, change to data.minusDays(7);
final String formattedDate = plusDays.format(DateTimeFormatter.ofPattern("MM/dd/yyyy")); // show is this format 09/30/2020
System.out.println(formattedDate); //09/30/2020
MinusDays
final LocalDate date = LocalDate.now();
final LocalDate minusDays = date.minusDays(7);
final String formattedDate = minusDays.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"));
System.out.println(formattedDate);
dateTimeFormat has a lot of features inside, refer to
https://howtodoinjava.com/java/date-time/java8-datetimeformatter-example/
I need to find the Last Friday of the previous month. This month is June. I need the last Friday of May. In this case (May 29th). I am able to only find the Last Friday of current month. After I find the previous month's Friday, I need to check from how many days has it been. If it has been 5 days since the last Friday, then execute a task. Hopefully this is clear. If not, please ask and I can explain in greater detail.
public class task {
static String lastFriday;
static String dtToday;
public static void main(String[] args) {
//daysInBetween = current day - (last month's friday date)
if (daysInBetween = 5) {
//run program after 5 days
} else { //quit program }
}
// Gets last Friday of the Month
// Need last Friday of previous Month...
public static String getLastFriday() {
Calendar cal = new GregorianCalendar();
cal.set(GregorianCalendar.DAY_OF_WEEK, Calendar.FRIDAY);
cal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);
SimpleDateFormat date_format = new SimpleDateFormat("yyyy/MM/dd");
lastFriday = date_format.format(cal.getTime());
return lastFriday;
}
// Gets today's date
public static String getToday() {
Calendar cal = new GregorianCalendar();
SimpleDateFormat date_format = new SimpleDateFormat("yyyy/MM/dd");
dtToday = date_format.format(cal.getTime());
return dtToday;
}
}
Find last Friday of any month using the method -
public Date getLastFriday( int month, int year ) {
Calendar cal = Calendar.getInstance();
cal.set( year, month + 1, 1 );
cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );
return cal.getTime();
}
And you may use the following method to find the diffrence between 2 days -
public int getDifferenceDays(Date d1, Date d2) {
int daysdiff=0;
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000)+1;
daysdiff = (int) diffDays;
return daysdiff;
}
You was nearly there, just add the follwing line to your getLastFriday method:
// Gets last Friday of the Month
// Need last Friday of previous Month...
public static String getLastFriday() {
Calendar cal = new GregorianCalendar();
// reduce the "current" month by 1 to get the "previous" month
cal.set(GregorianCalendar.MONTH, cal.get(GregorianCalendar.MONTH) - 1);
cal.set(GregorianCalendar.DAY_OF_WEEK, Calendar.FRIDAY);
cal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);
SimpleDateFormat date_format = new SimpleDateFormat("yyyy/MM/dd");
lastFriday = date_format.format(cal.getTime());
return lastFriday;
}
Then you can read one of these question and their answers to get the difference in days: Finding days difference in java or Calculating the difference between two Java date instances.
I want to display the current date and last 5 days dates
2013/04/24
2013/04/23
2013/04/22
2013/04/21
2013/04/20
I have code as below..
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
for (int i=0;i<5;i++){
cal.add(Calendar.DAY_OF_MONTH,-1);
date=cal.getTime();
String reportDate = sdf.format(date);
System.out.println("reportDate :" + reportDate);
}
Here i am getting output like below..
reportDate :2013/04/23
reportDate :2013/04/22
reportDate :2013/04/21
reportDate :2013/04/20
reportDate :2013/04/19
but i want last five days dates including current date...can any one help?
Try this!!
public static void getDate(){
GregorianCalendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
int day = cal.get(GregorianCalendar.DAY_OF_MONTH);
for(int i=day; i > (day-5); i--){
cal.set(GregorianCalendar.DAY_OF_MONTH, i);
Date date = cal.getTime();
System.out.println(sdf.format(date));
}
}
v 2.0
public static void getDate1(){
GregorianCalendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
cal.set(2013, 0, 1); // this is extreme case!!!
int day = cal.get(GregorianCalendar.DAY_OF_MONTH);
int month = cal.get(GregorianCalendar.MONTH);
int year = cal.get(GregorianCalendar.YEAR);
for(int i=day; i > (day-5); i--){
cal.set(year, month, i);
Date date = cal.getTime();
System.out.println(sdf.format(date));
}
}
This is the Output:
2013/01/01
2012/12/31
2012/12/30
2012/12/29
2012/12/28
The problem is this line:
cal.add(Calendar.DAY_OF_MONTH,-i);
Specifically the -i part. In the first iteration, i is 0 so you don't subtract any days. In the next you subtract one day, so you get the 23rd. In the next, you subtract two days, so you get the 21st, and so on.
You want to print out the initial date, then loop four times subtracting one day each in each iteration, so:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String reportDate = sdf.format(date);
System.out.println("reportDate :" + reportDate);
for (int i = 0; i < 4; i++) {
cal.add(Calendar.DAY_OF_MONTH, -1);
date = cal.getTime();
reportDate = sdf.format(date);
System.out.println("reportDate :" + reportDate);
}
Your subtracting the value of i in each iteration. And i increases by 1 each iteration. You probably just want to subtract 1 regardless of i.
cal.add(Calendar.DAY_OF_MONTH, -1);
Edit
Or maybe even a better solution
cal.roll(Calendar.DAY_OF_MONTH, false);
I need the start date and the end date of the current month in Java. When the JSP page is loaded with the current month it should automatically calculate the start and end date of that month. It should be irrespective of the year and month. That is some month has 31 days or 30 days or 28 days. This should satisfy for a leap year too. Can you help me out with that?
For example if I select month May in a list box I need starting date that is 1 and end date that is 31.
There you go:
public Pair<Date, Date> getDateRange() {
Date begining, end;
{
Calendar calendar = getCalendarForNow();
calendar.set(Calendar.DAY_OF_MONTH,
calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
setTimeToBeginningOfDay(calendar);
begining = calendar.getTime();
}
{
Calendar calendar = getCalendarForNow();
calendar.set(Calendar.DAY_OF_MONTH,
calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setTimeToEndofDay(calendar);
end = calendar.getTime();
}
return Pair.of(begining, end);
}
private static Calendar getCalendarForNow() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(new Date());
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);
}
private static void setTimeToEndofDay(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
}
PS: Pair class is simply a pair of two values.
If you have the option, you'd better avoid the horrid Java Date API, and use instead Jodatime (or equivalently the Java 8 java.time.* API). Here is an example:
LocalDate monthBegin = new LocalDate().withDayOfMonth(1);
LocalDate monthEnd = new LocalDate().plusMonths(1).withDayOfMonth(1).minusDays(1);
Try LocalDate from Java 8:
LocalDate today = LocalDate.now();
System.out.println("First day: " + today.withDayOfMonth(1));
System.out.println("Last day: " + today.withDayOfMonth(today.lengthOfMonth()));
Simple and Best, Try this One
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 0);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date monthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date monthLastDay = calendar.getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String startDateStr = df.format(monthFirstDay);
String endDateStr = df.format(monthLastDay);
Log.e("DateFirstLast",startDateStr+" "+endDateStr);
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = 1;
c.set(year, month, day);
int numOfDaysInMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("First Day of month: " + c.getTime());
c.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth-1);
System.out.println("Last Day of month: " + c.getTime());
With the date4j library :
dt.getStartOfMonth();
dt.getEndOfMonth();
Try this Code
Calendar calendar = Calendar.getInstance();
int yearpart = 2010;
int monthPart = 11;
int dateDay = 1;
calendar.set(yearpart, monthPart, dateDay);
int numOfDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("Number of Days: " + numOfDaysInMonth);
System.out.println("First Day of month: " + calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth-1);
System.out.println("Last Day of month: " + calendar.getTime());
Hope it helps.
if you have java.time.YearMonth you can do:
YearMonth startYearMonth = YearMonth.now();
java.time.LocalDate startOfMonthDate = startYearMonth.atDay(1);
java.time.LocalDate endOfMonthDate = startYearMonth.atEndOfMonth();
Date begining, ending;
Calendar calendar_start =BusinessUnitUtility.getCalendarForNow();
calendar_start.set(Calendar.DAY_OF_MONTH,calendar_start.getActualMinimum(Calendar.DAY_OF_MONTH));
begining = calendar_start.getTime();
String start= DateDifference.dateToString(begining,"dd-MMM-yyyy");//sdf.format(begining);
// for End Date of month
Calendar calendar_end = BusinessUnitUtility.getCalendarForNow();
calendar_end.set(Calendar.DAY_OF_MONTH,calendar_end.getActualMaximum(Calendar.DAY_OF_MONTH));
ending = calendar_end.getTime();
String end=DateDifference.dateToString(ending,"dd-MMM-yyyy");//or sdf.format(end);
enter code here
public static Calendar getCalendarForNow() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(new Date());
return calendar;
}
For Java 8+, below method will given current month first & last dates as LocalDate instances.
public static LocalDate getCurrentMonthFirstDate() {
return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).withDayOfMonth(1);
}
public static LocalDate getCurrentMonthLastDate() {
return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).plusMonths(1).withDayOfMonth(1).minusDays(1);
}
Side note: Using LocalDate.ofEpochDay(...) instead of LocalDate.now() gives much improved performance. Also, using the millis-in-a-day expression instead of the end value, which is 86400000 is performing better. I initially thought the latter would perform better than the the expression :P
public static void main(String[] args)
{
LocalDate today = LocalDate.now();
System.out.println("First day: " +
today.withDayOfMonth(1));
System.out.println("Last day: " + today.withDayOfMonth(today.lengthOfMonth()))
}
You can implement it as below:
public void FirstAndLastDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
//start date of month
calendarStart = Calendar.getInstance();
calendarStart.set(Integer.parseInt((new SimpleDateFormat("yyyy")).format(new Date().getTime()))
, Integer.parseInt((new SimpleDateFormat("MM")).format(new Date().getTime()))
, Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
//End Date of month
calendarEnd = Calendar.getInstance();
calendarEnd.set(Integer.parseInt((new SimpleDateFormat("yyyy")).format(new Date().getTime()))
, Integer.parseInt((new SimpleDateFormat("MM")).format(new Date().getTime()))
, Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
Toast.makeText(this, sdf.format(calendarStart.getTime()) + "\n" + sdf.format(calendarEnd.getTime()), Toast.LENGTH_SHORT).show();
}
A very simple step to get the first day and last day of the month:
Calendar calendar = Calendar.getInstance();
// Get the current date
Date today = calendar.getTime();
// Setting the first day of month
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date firstDayOfMonth = calendar.getTime();
// Move to next month
calendar.add(Calendar.MONTH, 1);
// setting the 1st day of the month
calendar.set(Calendar.DAY_OF_MONTH, 1);
// Move a day back from the date
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
// Formatting the date
DateFormat sdf = new SimpleDateFormat("dd-MMM-YY");
String todayStr = sdf.format(today);
String firstDayOfMonthStr = sdf.format(firstDayOfMonth);
String lastDayOfMonthStr = sdf.format(lastDayOfMonth);
System.out.println("Today : " + todayStr);
System.out.println("Fist Day of Month: "+firstDayOfMonthStr);
System.out.println("Last Day of Month: "+lastDayOfMonthStr);
Making it more modular, you can have one main function that calculates startDate or EndDate and than you can have individual methods to getMonthStartDate, getMonthEndDate and to getMonthStartEndDate. Use methods as per your requirement.
public static String getMonthStartEndDate(){
String start = getMonthDate("START");
String end = getMonthDate("END");
String result = start + " to " + end;
return result;
}
public static String getMonthStartDate(){
String start = getMonthDate("START");
return start;
}
public static String getMonthEndDate(){
String end = getMonthDate("END");
return end;
}
/**
* #param filter
* START for start date of month e.g. Nov 01, 2013
* END for end date of month e.g. Nov 30, 2013
* #return
*/
public static String getMonthDate(String filter){
String MMM_DD_COMMA_YYYY = "MMM dd, yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(MMM_DD_COMMA_YYYY);
sdf.setTimeZone(TimeZone.getTimeZone("PST"));
sdf.format(GregorianCalendar.getInstance().getTime());
Calendar cal = GregorianCalendar.getInstance();
int date = cal.getActualMinimum(Calendar.DATE);
if("END".equalsIgnoreCase(filter)){
date = cal.getActualMaximum(Calendar.DATE);
}
cal.set(Calendar.DATE, date);
String result = sdf.format(cal.getTime());
System.out.println(" " + result );
return result;
}