Issue with date increment - java

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

Related

Joda's DateTime is inconsistent with java.util.Calendar

I use the following code to check the consistency between joda's DateTime and java.util.Calendar. This result is correct, but if I change the year 2000 to 1900, then I will get 2 different result. Is this a bug or something else cause this ?
Calendar c = Calendar.getInstance();
c.set(1900,0,1,0,0,0); // Calendar's month is 0 based
c.set(Calendar.MILLISECOND, 0);
System.out.println(c.getTimeInMillis() / 1000);
DateTime dt = new DateTime(1900,1,1,0,0,0); // joda's month is 1 based
System.out.println(dt.getMillis() / 1000);
And this is the output
-2209017600
-2209017943
It's something else :)
import org.joda.time.DateTime;
import java.util.Calendar;
public class DateTester {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
c.set(1900,0,1,0,0,0);
c.set(Calendar.MILLISECOND, 0);
System.out.println(c.getTimeInMillis()/1000);
DateTime dt = new DateTime(1900,1,1,0,0,0);
System.out.println(dt.getMillis()/1000);
}
}
result:
-2208992400
-2208992400
Process finished with exit code 0
It has to do with offset between UTC and your timezone. For my timezone it is 1893
import org.joda.time.DateTime;
import java.util.Calendar;
public class DateTester {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
int i = 1900;
boolean found = false;
while (!found) {
c.set(i,0,1,0,0,0);
c.set(Calendar.MILLISECOND, 0);
DateTime dt = new DateTime(i,1,1,0,0,0);
found = !(c.getTimeInMillis() == dt.getMillis());
if (found) {
System.out.println("year: " + i);
System.out.println(c.getTimeInMillis());
System.out.println(dt.getMillis());
}
i--;
}
}
}
Result:
year: 1893
-2429830800000
-2429830408000
This offset between UTC and set time-zone can be checked in time zone data base

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

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

How to calculate a full days difference between two dates considering daylight savings in java

I need to get the full days between two dates in java (the dates are given in Date type) .
For example:
01/01/2015/12:00:00 - 01/02/2015/11:59:00 isn't a full day
and i need to consider daylight savings.
I know that jodatime lib does that but i reached the 65k method limit and i cant use jodatime lib.
i tried the millisecond diff way and the while loop that uses the "before" method:
Android/Java - Date Difference in days
I manage to figure it out:
i used some of this code - https://stackoverflow.com/a/28865648/3873513
and added some of mine:
public static int calcDaysDiff(Date day1, Date day2) {
Date d1 = new Date(day1.getTime());
Date d2 = new Date(day2.getTime());
Calendar date1 = Calendar.getInstance();
date1.setTime(d1);
Calendar date2 = Calendar.getInstance();
date2.setTime(d2);
//checks if the start date is later then the end date - gives 0 if it is
if (date1.get(Calendar.YEAR) >= date2.get(Calendar.YEAR)) {
if (date1.get(Calendar.DAY_OF_YEAR) >= date2.get(Calendar.DAY_OF_YEAR)) {
return 0;
}
}
//checks if there is a daylight saving change between the two dates
int offset = calcOffset(d1, d2);
if (date1.get(Calendar.YEAR) > date2.get(Calendar.YEAR)) {
//swap them
Calendar temp = date1;
date1 = date2;
date2 = temp;
}
return calcDaysDiffAux(date1, date2) + checkFullDay(date1, date2, offset);
}
// check if there is a 24 hour diff between the 2 dates including the daylight saving offset
public static int checkFullDay(Calendar day1, Calendar day2, int offset) {
if (day1.get(Calendar.HOUR_OF_DAY) <= day2.get(Calendar.HOUR_OF_DAY) + offset) {
return 0;
}
return -1;
}
// find the number of days between the 2 dates. check only the dates and not the hours
public static int calcDaysDiffAux(final Calendar day1, final Calendar day2) {
Calendar dayOne = (Calendar) day1.clone(),
dayTwo = (Calendar) day2.clone();
if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
} else {
int extraDays = 0;
while (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
dayTwo.add(Calendar.YEAR, -1);
// getActualMaximum() important for leap years
extraDays += dayTwo.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return extraDays - day1.get(Calendar.DAY_OF_YEAR) + day2.get(Calendar.DAY_OF_YEAR);
}
}
public class DateDiff {
public static void main(String[] av) {
SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy/HH:mm:ss");
String inputString1 = "01/01/2015/12:00:00";
String inputString2 = "01/02/2015/11:59:00";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime(); // Calculate the different
int days = (int) (diff / (1000*60*60*24)); // This convert milliseconds to days
System.out.println ("Days differ: " + days);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The following code will calculate the two dates given, the result print is:
Days differ: 0

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

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

Categories

Resources