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?
This question already has answers here:
How to get last month/year in java?
(10 answers)
Closed 7 years ago.
First i set month and year then i want previous month and year not current month. now i getting which month set on calender that month only
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class PrevMonth
{
private static String prev_day_str;
private static String prev_month_str;
public static void main(String[] args)
{
SimpleDateFormat prev_day = new SimpleDateFormat("dd");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 1);
calendar.set(Calendar.YEAR, 2015);
calendar .add(Calendar.MONTH, -1); //subtracting a month
SimpleDateFormat prev_month = new SimpleDateFormat("MM");
SimpleDateFormat prev_year = new SimpleDateFormat("YYYY");
prev_day_str = prev_month.format(new Date(calendar .getTimeInMillis()));
prev_month_str = prev_year.format(new Date(calendar .getTimeInMillis()));
System.out.println(prev_day_str+" "+prev_month_str);
}
}
Result:
01 2015
need for 12 2014
Your code:
calendar.set(Calendar.MONTH, 1);
actually sets the month to February.
For January you need to use 0, ie.
calendar.set(Calendar.MONTH, 0);
You start by initialize the calendar to February instead of January :
public class PrevMonth {
private static String prev_day_str;
private static String prev_month_str;
public static void main(String[] args)
{
SimpleDateFormat prev_day = new SimpleDateFormat("dd");
Calendar calendar = Calendar.getInstance();
// 0 for January
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.YEAR, 2015);
// -1 for substruct
calendar .add(Calendar.MONTH, -1); //subtracting a month
SimpleDateFormat prev_month = new SimpleDateFormat("MM");
SimpleDateFormat prev_year = new SimpleDateFormat("YYYY");
prev_day_str = prev_month.format(new Date(calendar .getTimeInMillis()));
prev_month_str = prev_year.format(new Date(calendar .getTimeInMillis()));
System.out.println(prev_day_str+" "+prev_month_str);
}
}
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.
In android,I have a String of that format "2015-03-30T12:30:00" and I want to know which day of the week it is.
Testing with the device on the same day, with that function dayOfweek = 5 and dayOfWeek2 = 2 why?
if I try to create a new Date with year , month , day Its say is deprecated...
public int devolverDia(String hora)
{
hora = hora.substring(0, 10);
String weekdays[] = new DateFormatSymbols(Locale.ENGLISH).getWeekdays();
Calendar c = Calendar.getInstance();
int year = Integer.parseInt(hora.substring(0, 4));
int month = Integer.parseInt(hora.substring(5, 7));
int day = Integer.parseInt(hora.substring(8, 10));
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
c.setTime(new Date());
int dayOfWeek2 = c.get(Calendar.DAY_OF_WEEK);
return dayOfWeek;
}
The reason that you don't get the date that you expect is that the line
c.set(Calendar.MONTH, month);
expects a month number from 0 (for January) to 11 (for December). If you replace it with
c.set(Calendar.MONTH, month - 1);
this code will work.
However, a much better solution would be to use the parse method of the SimpleDateFormat class to convert your String to a Date.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
c.setTime(format.parse(hora));
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;
}