Get interval date in Android? - java

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

Related

how to highlights specific dates in CalendarView in android studio?

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

How can I convert Calendar value to String in android studio?

I have Calendar value which is from Date Picker and I want to convert this value to String format "yyyy-MM-dd"
This is my Date Picker code. I save the selected values to startYear, startMonth and startDay.
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
and then I tried to convert these values to String in this way. But the log result is 0002-12-31 not what I selected from Date Picker.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
Never use Calendar. That terrible class was supplanted years ago by the modern java.time classes.
LocalDate
Instead, use LocalDate for a date-only value with no time-of-day and no offset or time zone.
LocalDate x = LocalDate.now() ;
String output = x.toString() ;
Build from parts.
LocalDate x = LocalDate.of( y , m , d ) ;
Get parts.
int y = x.getYear() ;
int m = x.getMonthValue() ;
int d = x.getDayOfMonth() ;
If your code goes like this; the log shows the date value before picking any dates. So you see the value for year: 0, month: 0 and day:0 (which is shown as 0002-12-31). (Note that the code inside onDateSet() method runs asynchronously, when the user picks a date.)
int startYear, startMonth, startDay;
Calendar today = GregorianCalendar.getInstance();
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
// startYear, startMonth, startDay are not initialized yet and equal 0.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
Instead; if you try to convert your Date to String "after the values are set" (Shown below) .You can see it will be correctly converted.
int startYear, startMonth, startDay;
Calendar today = GregorianCalendar.getInstance();
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
//************************************************************
//Now we have the picked values.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
//************************************************************
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
Let's see the simple code to convert Date to String
Basic
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String strDate = dateFormat.format(date);
System.out.println("Converted String: " + strDate);
Advanced
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
System.out.println("Date Format with MM/dd/yyyy : "+strDate);
formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
strDate = formatter.format(date);
System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
strDate = formatter.format(date);
System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);
}

adding date to calendar is not updating month [duplicate]

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

Android difference between two dates?

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.

How to check if a timestamp is late

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

Categories

Resources