i have tried most things online from custom calendar views to dependencies but they all lead to being outdated and not usable for android studio in its latest version.
does anyone know how to achieve this? I have tried mCalendarView, SunDeepK CalendarView and material-calendar view, but to no avail..
private void setCustomResourceForDates() {
Calendar cal = Calendar.getInstance();
//highlighlighting the holidays in a month taking the static dates
ArrayList<String> dates = new ArrayList<String>();
dates.add("02-08-2015");
dates.add("22-08-2015");
dates.add("17-09-2015");
dates.add("25-09-2015");
dates.add("27-09-2015");
dates.add("13-10-2015");
dates.add("22-10-2015");
SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
for (int i = 1; i < dates.size(); i++) {
inputString2 = dates.get(i);
inputString1 = myFormat.format(date);
try {
//Converting String format to date format
date1 = myFormat.parse(inputString1);
date2 = myFormat.parse(inputString2);
//Calculating number of days from two dates
long diff = date2.getTime() - date1.getTime();
long datee = diff / (1000 * 60 * 60 * 24);
//Converting long type to int type
day = (int) datee;
} catch (ParseException e) {
e.printStackTrace();
}
cal = Calendar.getInstance();
cal.add(Calendar.DATE, day);
holidayDay = cal.getTime();
colors();
}
}
public void colors() {
if (caldroidFragment != null) {
caldroidFragment.setBackgroundResourceForDate(R.color.green,
holidayDay);
caldroidFragment.setTextColorForDate(R.color.white, holidayDay);
}
}
}
call setCustomResourceForDates(); on onCreate method (in Caldroid Calendar
you can find it here : https://stackoverflow.com/a/32601769/20137896
Related
I want a Java program that calculates days between two dates.
Type the first date (German notation; with whitespaces: "dd mm yyyy")
Type the second date.
The program should calculates the number of days between the two dates.
How can I include leap years and summertime?
My code:
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class NewDateDifference {
public static void main(String[] args) {
System.out.print("Insert first date: ");
Scanner s = new Scanner(System.in);
String[] eingabe1 = new String[3];
while (s.hasNext()) {
int i = 0;
insert1[i] = s.next();
if (!s.hasNext()) {
s.close();
break;
}
i++;
}
System.out.print("Insert second date: ");
Scanner t = new Scanner(System.in);
String[] insert2 = new String[3];
while (t.hasNext()) {
int i = 0;
insert2[i] = t.next();
if (!t.hasNext()) {
t.close();
break;
}
i++;
}
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(insert1[0]));
cal.set(Calendar.MONTH, Integer.parseInt(insert1[1]));
cal.set(Calendar.YEAR, Integer.parseInt(insert1[2]));
Date firstDate = cal.getTime();
cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(insert2[0]));
cal.set(Calendar.MONTH, Integer.parseInt(insert2[1]));
cal.set(Calendar.YEAR, Integer.parseInt(insert2[2]));
Date secondDate = cal.getTime();
long diff = secondDate.getTime() - firstDate.getTime();
System.out.println ("Days: " + diff / 1000 / 60 / 60 / 24);
}
}
UPDATE: The original answer from 2013 is now outdated because some of the classes have been replaced. The new way of doing this is using the new java.time classes.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
LocalDateTime date1 = LocalDate.parse(inputString1, dtf);
LocalDateTime date2 = LocalDate.parse(inputString2, dtf);
long daysBetween = Duration.between(date1, date2).toDays();
System.out.println ("Days: " + daysBetween);
} catch (ParseException e) {
e.printStackTrace();
}
Note that this solution will give the number of actual 24 hour-days, not the number of calendar days. For the latter, use
long daysBetween = ChronoUnit.DAYS.between(date1, date2)
Original answer (outdated as of Java 8)
You are making some conversions with your Strings that are not necessary. There is a SimpleDateFormat class for it - try this:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
EDIT: Since there have been some discussions regarding the correctness of this code: it does indeed take care of leap years. However, the TimeUnit.DAYS.convert function loses precision since milliseconds are converted to days (see the linked doc for more info). If this is a problem, diff can also be converted by hand:
float days = (diff / (1000*60*60*24));
Note that this is a float value, not necessarily an int.
Simplest way:
public static long getDifferenceDays(Date d1, Date d2) {
long diff = d2.getTime() - d1.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}
In Java 8, you could accomplish this by using LocalDate and DateTimeFormatter. From the Javadoc of LocalDate:
LocalDate is an immutable date-time object that represents a date,
often viewed as year-month-day.
And the pattern can be constructed using DateTimeFormatter. Here is the Javadoc, and the relevant pattern characters I used:
Symbol - Meaning - Presentation - Examples
y - year-of-era - year - 2004; 04
M/L - month-of-year - number/text - 7; 07; Jul;
July; J
d - day-of-month - number - 10
Here is the example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class Java8DateExample {
public static void main(String[] args) throws IOException {
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MM yyyy");
final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
final String firstInput = reader.readLine();
final String secondInput = reader.readLine();
final LocalDate firstDate = LocalDate.parse(firstInput, formatter);
final LocalDate secondDate = LocalDate.parse(secondInput, formatter);
final long days = ChronoUnit.DAYS.between(firstDate, secondDate);
System.out.println("Days between: " + days);
}
}
Example input/output with more recent last:
23 01 1997
27 04 1997
Days between: 94
With more recent first:
27 04 1997
23 01 1997
Days between: -94
Well, you could do it as a method in a simpler way:
public static long betweenDates(Date firstDate, Date secondDate) throws IOException
{
return ChronoUnit.DAYS.between(firstDate.toInstant(), secondDate.toInstant());
}
Most / all answers caused issues for us when daylight savings time came around. Here's our working solution for all dates, without using JodaTime. It utilizes calendar objects:
public static int daysBetween(Calendar day1, 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 {
if (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
//swap them
Calendar temp = dayOne;
dayOne = dayTwo;
dayTwo = temp;
}
int extraDays = 0;
int dayOneOriginalYearDays = dayOne.get(Calendar.DAY_OF_YEAR);
while (dayOne.get(Calendar.YEAR) > dayTwo.get(Calendar.YEAR)) {
dayOne.add(Calendar.YEAR, -1);
// getActualMaximum() important for leap years
extraDays += dayOne.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return extraDays - dayTwo.get(Calendar.DAY_OF_YEAR) + dayOneOriginalYearDays ;
}
}
The best way, and it converts to a String as bonus ;)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//Dates to compare
String CurrentDate= "09/24/2015";
String FinalDate= "09/26/2015";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy");
//Setting dates
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
//Comparing dates
long difference = Math.abs(date1.getTime() - date2.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
Log.e("HERE","HERE: " + dayDifference);
}
catch (Exception exception) {
Log.e("DIDN'T WORK", "exception " + exception);
}
}
Use:
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;
}
Java date libraries are notoriously broken. I would advise to use Joda Time. It will take care of leap year, time zone and so on for you.
Minimal working example:
import java.util.Scanner;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class DateTestCase {
public static void main(String[] args) {
System.out.print("Insert first date: ");
Scanner s = new Scanner(System.in);
String firstdate = s.nextLine();
System.out.print("Insert second date: ");
String seconddate = s.nextLine();
// Formatter
DateTimeFormatter dateStringFormat = DateTimeFormat
.forPattern("dd MM yyyy");
DateTime firstTime = dateStringFormat.parseDateTime(firstdate);
DateTime secondTime = dateStringFormat.parseDateTime(seconddate);
int days = Days.daysBetween(new LocalDate(firstTime),
new LocalDate(secondTime)).getDays();
System.out.println("Days between the two dates " + days);
}
}
String dateStart = "01/14/2015 08:29:58";
String dateStop = "01/15/2015 11:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
want to get just days(no times) you can use ChronoUnit
ChronoUnit.DAYS.between(date1.toLocalDate(), date2.toLocalDate());
We can make use of LocalDate and ChronoUnit java library, Below code is working fine.
Date should be in format yyyy-MM-dd.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
class Solution {
public int daysBetweenDates(String date1, String date2) {
LocalDate dt1 = LocalDate.parse(date1);
LocalDate dt2= LocalDate.parse(date2);
long diffDays = ChronoUnit.DAYS.between(dt1, dt2);
return Math.abs((int)diffDays);
}
}
When I run your program, it doesn't even get me
to the point where I can enter the second date.
This is simpler and less error prone.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test001 {
public static void main(String[] args) throws Exception {
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(System.in));
SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy");
System.out.println("Insert first date : ");
Date dt1 = sdf.parse(br.readLine().trim());
System.out.println("Insert second date : ");
Date dt2 = sdf.parse(br.readLine().trim());
long diff = dt2.getTime() - dt1.getTime();
System.out.println("Days: " + diff / 1000L / 60L / 60L / 24L);
if (br != null) {
br.close();
}
}
}
// date format, it will be like "2015-01-01"
private static final String DATE_FORMAT = "yyyy-MM-dd";
// convert a string to java.util.Date
public static Date convertStringToJavaDate(String date)
throws ParseException {
DateFormat dataFormat = new SimpleDateFormat(DATE_FORMAT);
return dataFormat.parse(date);
}
// plus days to a date
public static Date plusJavaDays(Date date, int days) {
// convert to jata-time
DateTime fromDate = new DateTime(date);
DateTime toDate = fromDate.plusDays(days);
// convert back to java.util.Date
return toDate.toDate();
}
// return a list of dates between the fromDate and toDate
public static List<Date> getDatesBetween(Date fromDate, Date toDate) {
List<Date> dates = new ArrayList<Date>(0);
Date date = fromDate;
while (date.before(toDate) || date.equals(toDate)) {
dates.add(date);
date = plusJavaDays(date, 1);
}
return dates;
}
The following works perfectly well for me:
public int daysBetween(LocalDate later, LocalDate before) {
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
int daysBetween = 0;
try {
Date dateBefore = myFormat.parse(localDateToString(before));
Date dateAfter = myFormat.parse(localDateToString(later));
long difference = dateAfter.getTime() - dateBefore.getTime();
daysBetween = (int) (difference / (1000 * 60 * 60 * 24));
} catch (Exception e) {
e.printStackTrace();
}
return daysBetween;
}
public String localDateToString(LocalDate date) {
DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("dd MM yyyy");
return date.format(myFormat).toString();
}
All the other answers had lots of scary things, here's my simple solution:
public int getDaysDiff(Date dateToCheck)
{
long diffMilliseconds = new Date().getTime() - dateToCheck.getTime();
double diffSeconds = diffMilliseconds / 1000;
double diffMinutes = diffSeconds / 60;
double diffHours = diffMinutes / 60;
double diffDays = diffHours / 24;
return (int) Math.round(diffDays);
}
public class TestCode {
public static void main(String[] args) {
String date1 = "23-04-2021";
String date2 = "24-05-2021";
System.out.println("NDays: " + nDays_Between_Dates(date1, date2));
}
public static int nDays_Between_Dates(String date1, String date2) {
int diffDays = 0;
try {
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
Date startDate = dates.parse(date1);
Date endDate = dates.parse(date2);
long diff = endDate.getTime() - startDate.getTime();
diffDays = (int) (diff / (24 * 60 * 60 * 1000));
} catch (ParseException e) {
e.printStackTrace();
}
return Math.abs(diffDays);
}
}
Output: NDays: 31
public static String dateCalculation(String getTime, String dependTime) {
//Time A is getTime that need to calculate.
//Time B is static time that Time A depend on B Time and calculate the result.
Date date = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd H:mm:ss");
Date dateObj = null;
Date checkDate = null;
try {
dateObj = sdf.parse(getTime);
} catch (ParseException e) {
e.printStackTrace();
return "0";
}
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String checkInDate = dateFormat.format(dateObj).toString();
Date defaultTime = null;
try {
defaultTime = dateFormat.parse(dependTime);
checkDate = dateFormat.parse(checkInDate);
} catch (ParseException e) {
e.printStackTrace();
return "0";
}
try {
if (dateFormat.parse(dateFormat.format(date)).after(defaultTime)) {
long diff = checkDate.getTime() - defaultTime.getTime();
Log.e("Difference", "onBindViewHolder: Difference: " + dateObj + " : " + defaultTime + " : " + diff);
if (diff > 0) {
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
return "Late: " + diffHours + " Hour, " + diffMinutes + " Minutes, " + diffSeconds + " Sec";
} else {
return "0";
}
}
} catch (ParseException e) {
e.printStackTrace();
return "0";
}
return "0";
}
This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 6 years ago.
I'm working on an android application and new to it.
I have to get date from user and then add 28 days and store it in database.
This is what I have done so far
private void saveDate() throws ParseException {
DatabaseHelper db = new DatabaseHelper(ActivityPeriodToday.this.getActivity());
String pDate = periodDate.getText().toString().trim();
String pTime = periodTime.getText().toString().trim();
String next_expected = getNextExpected(pDate);
boolean isInserted = db.insertPeriodTodayIntoPeriods(pDate, pTime, early_late, pDifference, pType, next_expected);
if (isInserted == true) {
Toast.makeText(ActivityPeriodToday.this.getActivity(), "Saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ActivityPeriodToday.this.getActivity(), "Could not be saved", Toast.LENGTH_SHORT).show();
}
}
private String getNextExpected(String pDate) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(pDate));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DAY_OF_MONTH, 28);
return sdf.format(c.getTime());
}
But is code is not incrementing month.
Ex. If user selects 01/11/2016, then date is incremented and is saved
29/11/2016. But if user selects 16/11/2016 then saves date is
28/11/2016 but this should be 14/12/2016
Step 1
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dateInString));
Step-2 use add() to add number of days to calendar
c.add(Calendar.DATE, 40);
Try using this:
calendar.add(Calendar.DAY_OF_YEAR, 28);
Its Working for me.
Calendar c = Calendar.getInstance();
int Year = c.get(Calendar.YEAR);
int Month = c.get(Calendar.MONTH);
int Day = c.get(Calendar.DAY_OF_MONTH);
// current date
String CurrentDate = Year + "/" + Month + "/" + Day;
String dateInString = CurrentDate; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dateInString));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DATE, 28);//insert the number of days that you want
sdf = new SimpleDateFormat("dd/MM/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
dateInString = sdf.format(resultdate);
Toast.makeText(MainActivity.this, ""+dateInString, Toast.LENGTH_SHORT).show();
Your question may already have an answer here: How can I increment a date by one day in Java?
Or you can simply use
c.add(Calendar.DATE, 28);
instead of
c.add(Calendar.DAY_OF_MONTH, 28);
I getting two date from calendars.It writing into a string builder.I want to getting difference between two date also I want to keep the number of days remaining between times,except weekends.
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
if (cur == DATE_DIALOG_ID) {
// set selected date into textview
permitDate = new StringBuilder().append(day).append(".").append(month + 1).append(".").append(year).append(" ").toString();
tvDisplayDate.setText("Date : " + permitDate);
} else {
startDate = new StringBuilder().append(day).append(".").append(month + 1) .append(".").append(year).append(" ").toString();
tvDisplayDate2.setText("Date : " + startDate);
}
}
};
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);
To Parse the date from a string, you could use
String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
Use JodaTime library to find the difference between dates.
For more information follow the instructions Use Joda Time.
I have a timestamp and I want to check whether the time is before or after a certain time (9:00 AM). To be more specific, I want to know whether a person is late or not and the cut-off time is 9 AM. How do I code this?
2015-09-22 08:59:59 //Print on time
2015-09-22 09:00:00 //Print on time
2015-09-22 09:00:01 //Print you are late
I think you can do like:
public static final String TIME_STAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static void main(String[] args) {
Date standard = getStandardDate();
SimpleDateFormat format = new SimpleDateFormat(TIME_STAMP_FORMAT);
List<String> data = new ArrayList<String>();
data.add("2015-09-22 08:59:59");
data.add("2015-09-22 09:00:00");
data.add("2015-09-22 09:00:01");
for (String date : data) {
if(isLate(date, format)) {
System.out.println(date + " is Late");
} else {
System.out.println(date + " is On Time");
}
}
}
/**
* check is Late or not
* */
public static boolean isLate(String date, SimpleDateFormat format) {
Date standard = getStandardDate();
Date inputDate = null;
boolean result = false;
try {
inputDate = format.parse(date);
if(inputDate.after(standard)) {
result = true;
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
/**
* get standard date
* */
public static Date getStandardDate() {
Date dateNow = new Date ();
Calendar cal = Calendar.getInstance();
cal.setTime(dateNow);
cal.set(Calendar.DAY_OF_MONTH, 22);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
Hope this help!
You can have code similar to following
// Get the provided date and time
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar providedDate = Calendar.getInstance();
providedDate.setTime(df.parse(stringInstanceRepresentingDate));
// Get the current date and time
Calendar cal = Calendar.getInstance();
// Set time of calendar to 09:00
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// Check if current time is after 09:00 today
boolean afterNine = providedDate.after(cal);
if (afterNine ) {
System.out.println("You are late");
}
else {
System.out.println("You are not late");
}
Assuming the input is a String, you can do the following
String input = ...;
String time = input.split(" ")[1],
hour = time.split(":")[0],
minute = time.split(":")[1],
seconds = time.split(":")[2];
if(Integer.parseInt(hour) > 9 && Integer.parseInt(minute) > 0) {
// Not on time
}
This is assuming the input is always perfect though, you should use try-catch blocks or check the input beforehand as this could throw exceptions.
LocalDateTime time = LocalDateTime.of(2015, 9, 22, 9, 0, 0);
LocalDateTime now = LocalDateTime.now();
if (now.compareTo(time) > 0)
System.out.println("You are late");
else System.out.println("You are in time");
If you are working with strings you have to split them first, as mentioned by #Deximus
I want interval date. Whatever user enter date from date picker and from this date I want to get after one month date Suppose 1 Aug 2014 -> Output will be 1 September 2014.Can someone help me .Thanks to appreciate.
Hare is my Activity code
{
// Get current date by calender
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Month is 0 based, just add 1
etReplacementDate.setText(new StringBuilder()
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
etReplacementDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showDialog(DATE_OF_REPLACEMENT);
}
});
String fixedDate = etReplacementDate.getText().toString().trim();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try
{
convertedDate = dateFormat.parse(fixedDate);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Date Consersion = " + convertedDate);
/****************ReplaceMent Date***************************************************/
cal2.add(Calendar.getInstance(convertedDate), 30);
Date date_30dayslater = cal2.getTime();
System.out.println("date_30dayslater : " + date_30dayslater);
/****************Interval Date***************************************************/
String _30daysLater_String = new SimpleDateFormat("yyyy-MM-dd").format(date_30dayslater);
etNextReplanishmentDate.setText(_30daysLater_String);
System.out.println("30 days later: " + _30daysLater_String);
System.out.println("______________________________________");
/****************Before Date***************************************************/
cal2.add(Calendar.DATE, -1);
Date beforDate = cal2.getTime();
String beforDate_String = new SimpleDateFormat("yyyy-MM-dd").format(beforDate);
System.out.println("beforDate_String: " + beforDate_String);
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DATE_OF_REPLACEMENT:return new DatePickerDialog(this, pickerListenerReplacement, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListenerReplacement = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
etReplacementDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
}
What you want to do is add() one Calendar.MONTH to a date that you've gotten and parsed, etc. so I won't go into that. I'll assume you are handling everything correctly up to the point where you'd like to get the same day, if possible, of the next month.
Part of your problem, as your comment suggests, is Calendar.getInstance() does not have an implementation that takes a Date. But more importantly you don't need it. You have a Date and a Calendar instance and it seems like you're changing c2 anyway so why not use Calendar's setTime() method like this?
// setting c2 with the convertedDate then adding a month
c2.setTime(convertedDate);
c2.add(Calendar.MONTH, 1);
// Simple example
public static void main(String...args) {
Date d = new Date();
Calendar c = Calendar.getInstance();
c.setTime(d);
System.out.println(c.getTime());
c.add(Calendar.MONTH, 1);
System.out.println(c.getTime());
}
try to use this.
Calendar c = Calendar.getInstance();
int month = c.get((Calendar.MONTH));
c.set(Calendar.MONTH, month + 1);
long time = c.getTimeInMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String result = sdf.format(new Date(time1));