How to get previous month date and year in java [duplicate] - java

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);
}
}

Related

I am getting different day of the week for the same date [duplicate]

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?

How to get current date and add five working days in Java [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
How can I add business days to the current date in Java?
(14 answers)
Closed 8 years ago.
I want two dates.
1) Current date in MM/dd/yy format
2) Modified date which will be the adition of five business days(Mon-Fri) to current date and it should be in MMM dd, yyyy format.
So if my current is 9th june than currentDate should be 06/09/14 and modifiedDate should be Jun 13, 2014.
How to do this?
This will add working days (Mon-Fri) and will present dates in the required format.
UPDATED 6 Jul 2020
Now custom days can be used as non working days (see the list NON_BUSINESS_DAYS)
Now even the past date can be calculated as well (set businessDays as negative val)
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class BusinessDateExamples {
private static final List<Integer> NON_BUSINESS_DAYS = Arrays.asList(
Calendar.SATURDAY,
Calendar.SUNDAY
);
/**
* Returns past or future business date
* #param date starting date
* #param businessDays number of business days to add/subtract
* <br/>note: set this as negative value to get past date
* #return past or future business date by the number of businessDays value
*/
public static Date businessDaysFrom(Date date, int businessDays) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
for (int i = 0; i < Math.abs(businessDays);) {
// here, all days are added/subtracted
calendar.add(Calendar.DAY_OF_MONTH, businessDays > 0 ? 1 : -1);
// but at the end it goes to the correct week day.
// because i is only increased if it is a week day
if (!NON_BUSINESS_DAYS.contains(calendar.get(Calendar.DAY_OF_WEEK))){
i++;
}
}
return calendar.getTime();
}
public static void main(String...strings) {
SimpleDateFormat s = new SimpleDateFormat("MM/dd/yy ( MMM dd, yyyy )");
Date date = new Date();
int businessDays = 5;
System.out.println(s.format(date));
System.out.print("+ " + businessDays + " Business Days = ");
System.out.println(s.format(businessDaysFrom(date, businessDays)));
System.out.print("- " + businessDays + " Business Days = ");
System.out.println(s.format(businessDaysFrom(date, -1 * businessDays)));
}
}
Date date=new Date();
Calendar calendar = Calendar.getInstance();
date=calendar.getTime();
SimpleDateFormat s;
s=new SimpleDateFormat("MM/dd/yy");
System.out.println(s.format(date));
int days = 5;
for(int i=0;i<days;)
{
calendar.add(Calendar.DAY_OF_MONTH, 1);
//here even sat and sun are added
//but at the end it goes to the correct week day.
//because i is only increased if it is week day
if(calendar.get(Calendar.DAY_OF_WEEK)<=5)
{
i++;
}
}
date=calendar.getTime();
s=new SimpleDateFormat("MMM dd, yyyy");
System.out.println(s.format(date));
Ref : https://stackoverflow.com/a/15339851/3603806
and https://stackoverflow.com/a/11356123/3603806
The notion of working days is not implemented in Java, it's too subject to interpretation (for example, many international companies have their own holidays). Code below uses isWorkingDay(), which only returns false for weekends - add your holidays there.
public class Test {
public static void main(String[] args) {
Calendar cal = new GregorianCalendar();
// cal now contains current date
System.out.println(cal.getTime());
// add the working days
int workingDaysToAdd = 5;
for (int i=0; i<workingDaysToAdd; i++)
do {
cal.add(Calendar.DAY_OF_MONTH, 1);
} while ( ! isWorkingDay(cal));
System.out.println(cal.getTime());
}
private static boolean isWorkingDay(Calendar cal) {
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY)
return false;
// tests for other holidays here
// ...
return true;
}
}
Here is the code sample to add dates. You may modify in order to you can only add business days.
SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMM dd, yyyy");
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
System.out.println(sdf1.format(calendar.getTime()));
calendar.add(Calendar.DATE,6);
System.out.println(sdf2.format(calendar.getTime()));

Issue with date increment

I am able to increment and decrement a date in my blackberry app.
The issue comes when I change some data in popup screen and click on next the date remains the same without incrementing however the long value is same as the incremented value.
Calendar calendar = Calendar.getInstance();
String dateFormat = compareDate; //mar 28,2012-compare date value
String m = dateFormat.substring(0, 3);
String dd = dateFormat.substring(4, 6);
String y = dateFormat.substring(7, 11);
dateFormat = dd + " " + m + " " + y; // 28 mar 2012
long dateLong = HttpDateParser.parse(dateFormat);
long ctimeMinus50Days = dateLong + 1L * ((long) DateTimeUtilities.ONEDAY);
calendar.setTime ( new Date(ctimeMinus50Days) );
System.out.println("ctimeMinus50Days" + ctimeMinus50Days);
Date d = calendar.getTime();
SimpleDateFormat sd1Exactform = new SimpleDateFormat("MMM dd,yyyy");
sd1Exactform.format(d);
if (dateCurrent != null) { //static value so making null before assigning new value
dateCurrent = null;
}
dateCurrent = sd1Exactform.format(d);
ctimeMinus50Days value is same when is works for increment, but when I see dateCurrent output it's the old date only even though long value shows incremented data.
You can use this class
public class DateUtilities {
static Calendar calendar = Calendar.getInstance();
public static long getPreviousDate(long currentDate){
calendar.setTime(new Date(currentDate));
calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 1);
return calendar.getTime().getTime();
}
public static long getNextDate(long currentDate){
calendar.setTime(new Date(currentDate));
calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
return calendar.getTime().getTime();
}
}
Calendar class exposes add method which you should use to add/subtract date elements. Here's an example to add one day to a date represented by the string:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test {
public static void main(String[] args) throws Exception{
String dateCurrent = "Mar 1,2012";
SimpleDateFormat sdExactform = new SimpleDateFormat("MMM d,yyyy");
Date date = sdExactform.parse(dateCurrent);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, 1);
System.out.println(calendar.toString());
}
}

Start and end date of a current month

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;
}

How to get week based on the date in java? [duplicate]

This question already has answers here:
how to identify the week from current date in java
(3 answers)
Closed 7 years ago.
I need to display week's start date. While selecting this week(28-12-2015), i am getting "29-12-2014" as start date because it is calculating based on week and year. Today's(28-12-2015) week i am getting as 1st week. I need to get last week of the year with the date as "27-12-2015" as start date.
Here is my code:
public Date getStartDate()
{
int weekNo = findWeekOfTheYear(new Date());
int year = findYear();
startDate = findStartDateUsingWeekAndYear(year, weekNo);
return startDate;
}
public int findYear()
{
Calendar calendar = new GregorianCalendar();
int year= calendar.get(Calendar.YEAR);
return year;
}
public int findWeekOfTheYear(Date date)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int weekOfMonth= calendar.get(Calendar.WEEK_OF_YEAR);
return weekOfMonth;
}
public Date findStartDateUsingWeekAndYear(int year,int week)
{
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.YEAR, year);
// Now get the first day of week.
Date date = calendar.getTime();
return date;
}
Any help?
Use
public Date findStartDateUsingWeekAndYear(int year,int week)
{
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.YEAR, year+1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
// Now get the first day of week.
Date date = calendar.getTime();
return date;
}
But if you want to get first day of current week, use
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
instead of
calendar.clear();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.YEAR, year);

Categories

Resources