Android: Calendar add days including month and year - android

I have a problem. I am using this code to "increase" or "decrease" one day. "value" is 1 or -1. I have tried c.add(Calendar.DAY_OF_MONTH, value); and c.add(Calendar.DATE, value); The problem is:
if value = 1, it increases day by 1 and month and year don't budge at all and remain same.
if value = -1, it decreases day by 1 and after 30 days it decrease the year.
I have tried everything but could not understand the behavior. I need to increase or decrease the whole date like it happens in MYSQL, not just date or month or year.
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(mDate));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DAY_OF_MONTH, value);
sdf = new SimpleDateFormat("dd/mm/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
String newDtString = sdf.format(resultdate);

You can try
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + value);
You'd also have to handle end cases when it's first or last day of year
Java handles this for you. Example:
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy");
calendar.setTimeZone(TimeZone.getDefault());
try {
calendar.setTime(sdf.parse("31 December 2015"));
} catch (ParseException e̋̋) { }
System.out.println(sdf.format(calendar.getTime()));
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + 1);
System.out.println(sdf.format(calendar.getTime()));
Prints:
31 December 2015
01 January 2016

Related

How to get date which is the sum of any previous date to 7 days next date?

I've a previous date from current date which is saved in database and need to get date 7 days next date. How can i get it?
For example:
i've date 1461560032085 milliseconds. How can i get 7 days next date?
It is very simple to use Calendar class
Calendar calendar = Calendar.getInstance();
calendar.setTime(your_current_date);
calendar.add(Calendar.DAY_OF_YEAR, +7);
Date newDate = calendar.getTime();
1 day = 86400000 milliseconds
So 7 days after "1461560032085" will be = 1461560032085 + 86400000 * 7
Hope this helps!
To calculate 7 days after the current day you should do the following:
nextWeek = yourdate + 7*24*60*60*1000
public static String getAdded_date(String previous_date){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(previous_date));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DAY_OF_WEEK, 7); // number of days to add, can also use Calendar.DAY_OF_MONTH in place of Calendar.DATE
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
String output = sdf1.format(c.getTime());
return output;
}
private int getaddedDate(int previousdate)
{
return previousdate + TimeUnit.DAYS.toMillis(7);
}

How to set alarm manager using date and time from Textview

I am converting a timestamp into date and time and setting the result on a textview.
For example 1443884578 is Sat 3 October 2015 18:02
I would like to set the above date and time into an alarm manager.After research i found a code that uses a date time picker.
public void onDateSelectedButtonClick(View v) {
// Get the date from our datepicker
int day = picker.getDayOfMonth();
int month = picker.getMonth();
int year = picker.getYear();
// Create a new calendar set to the date chosen
// we set the time to midnight (i.e. the first minute of that day)
Calendar c = Calendar.getInstance();
c.set(year, month, day);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
// Ask our service to set an alarm for that date, this activity talks to the client that talks to the service
scheduleClient.setAlarmForNotification(c);
// Notify the user what they just did
Toast.makeText(this, "Notification set for: " + day + "/" + (month + 1) + "/" + year, Toast.LENGTH_SHORT).show();
}
However its getting only the date and fires the alarm the minute the date occurs.
PROBLEM: I would like to get the date and time from my textview and skip this date time picker in the format i have. Is this possible?
String input = "Sat October 3 2015 18:02"; // Instead of String input = "Mon Feb 06 2015";
Calendar cal = Calendar.getInstance();
Date date = new Date();
// Changed the format to represent time of day
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
try {
date = sdf.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
cal.setTime(date);
//We haven't parsed the seconds from the original date so this will result
//in 18:02:00 - 10seconds.
//For a correct calculation, you could parse the seconds as well
//See SimpleDateFormat above, but you would have to provide the original date
//with seconds as well
cal.add(Calendar.SECOND, -10);
scheduleClient.setAlarmForNotification(cal);

Android date parsing (Extracting month and year )

I want my app to parse the date in format "dd-MMM-yyyy". The date has been successfully parsed when I try to get month and get year it is giving other result. I inpued 06-sep-2014 as date. But when I try to extract month and year from the parsed date it is showing 8 for month instead of 9 and 114 for year instead of 2014.
logcat output
6
8
114
Here's my code
String date1 = "06 sep 2014";
SimpleDateFormat format1 = new SimpleDateFormat("dd MMM yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("d MMM yyyy");
Date date;
try {
if (date1.length() == 11) {
date = format1.parse(date1);
} else {
date = format2.parse(date1);
}
int day=date.getDate();
int mon1=date.getMonth();
int year1=date.getYear();
System.out.println("date is:"+ date);
System.out.println(day);
System.out.println(mon1);
System.out.println(year1);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public final class DateParseDemo {
public static void main(String[] args){
final DateFormat df = new SimpleDateFormat("dd MMM yyyy");
final Calendar c = Calendar.getInstance();
try {
c.setTime(df.parse("06 sep 2014"));
System.out.println("Year = " + c.get(Calendar.YEAR));
System.out.println("Month = " + (c.get(Calendar.MONTH)));
System.out.println("Day = " + c.get(Calendar.DAY_OF_MONTH));
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
Output:
Year = 2014
Month = 8
Day = 6
And as for the month field, this is 0-based. This means that January = 0 and December = 11. As stated by the javadoc,
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
Because date.getyear Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
Maybe, You can use for example;
int year1=date.getYear();
System.out.println(year1+1900);
Using the Date class, it gives you the year starting from 1900. A better way to get what you want is using the Calendar class. See http://developer.android.com/reference/java/util/Date.html#getYear()

Calculating date certain period from now

I have a start date (day, month, year) and need the date say 4 weeks from that date. How can I calculate that? I know how to find the difference between two dates using Calendar so I assume I'm not too far from the answer... Thank you!!!
edit:
This is the final code I wound up using. It returns a String whose value is a date span formatted "MM/dd/YYYY - MM/dd/YYYY"
#SuppressLint("SimpleDateFormat")
private String getSessionDate(int position) {
MySession ms = mSessionList.get(position);
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.set(ms.getStartYear(), ms.getStartMonth(), ms.getStartDay());
Date startDate = calendar.getTime();
String durationString = ms.getDurationString(); // Format is "## weeks"
int i = 0;
while (Character.isDigit(durationString.charAt(i))) {
i++;
}
int weeks = Integer.parseInt(durationString.substring(0, i));
calendar.add(Calendar.WEEK_OF_YEAR, weeks);
return (format.format(startDate) + " - " + format.format(calendar.getTime()));
}
You can use Calender instance for that.
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentdate);
calendar.add(Calendar.DAY_OF_YEAR, no_of_days)
Date newDate = calendar.getTime();
You can calculate the date by adding or subtracting the no of days
Example :
Get date after 1 week
calendar.add(Calendar.DAY_OF_YEAR, 7);
Get date before 1 week
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date date=null;
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = originalFormat.parse(strDate); // strDate is your date from which you want to get date after 4 weeks
} catch (Exception e) {
e.printStackTrace();
}
long timeFor4week=4*7*24 * 60 * 60 * 1000; /// here 24*60*60*1000 =24 hours i.e 1 day
long timeAfter4week=date.getTime()+timeFor4week;
String finalDateString=originalFormat.format(new Date(timeAfter4week));
So you can get day after 4 weeks.

How to calculate date? I have of Days + Start Date and Find end Date

I am developing android application, in that application How to calculate the end date based on Start Date and No of days?E.g I have starting date Sep 13, 2012 if i add 45 days with that date I will get 27 October 2012.
How to do that?
I cannot use the date function inside if statement.
My code:
f (resCrop.equals("Paddy"))
{
if(rescultivation1.equals("Conventional method - Delta"))
{
if(resvariety1.equals("Short duration"))
{
WA.setVisibility(View.VISIBLE);
TONE.setVisibility(View.VISIBLE);
TTWO.setVisibility(View.VISIBLE);
TTHREE.setVisibility(View.VISIBLE);
//date calculation
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy");
Calendar c1 = Calendar.getInstance(); // Get Calendar Instance
try {
c1.setTime(sdf.parse(resDate));
} catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
c1.add(Calendar.DATE, 3); // add 3 days
sdf = new SimpleDateFormat("dd-M-yyyy");
Date resultdate = new Date(c1.getTimeInMillis()); // Get new time
String dateInString = sdf.format(resultdate);
WP.setText(dateInString);
WP.setEnabled(false);
Calendar c2 = Calendar.getInstance();
c2.add(Calendar.DATE, 35); // add 45 days
sdf = new SimpleDateFormat("dd-M-yyyy");
}
}
}
Its not working inside the if statement. if i used outside if its working fine. how to resolve this problem. please advice me.
Try this code . You can use any date format what you want.
String dateInString = "2011-09-13"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance(); // Get Calendar Instance
c.setTime(sdf.parse(dateInString));
c.add(Calendar.DATE, 45); // add 45 days
sdf = new SimpleDateFormat("MM/dd/yyyy");
Date resultdate = new Date(c.getTimeInMillis()); // Get new time
dateInString = sdf.format(resultdate);
System.out.println("String date:"+dateInString);
you can use the Below Code to Solve your Problem.
Calendar cal=Calendar.getInstance();
int currentDay=cal.get(Calendar.DAY_OF_MONTH);
//Set the date after 45 days
cal.set(Calendar.DAY_OF_MONTH, currentDay+45);
int EndDay=cal.get(Calendar.DAY_OF_MONTH);
Hello Madhan,
Plz Convert ur date into milli second and then differentiate it and divided it by 1000*60*60*24.
Please See the Code piece Like that
Date d1 = new Date(1st Date);
Date d2 = new Date(2nd Date);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(d1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(d2);
presumedDays = (int) ((cal2.getTimeInMillis() - cal1.getTimeInMillis()) / (1000 * 60 * 60 * 24));
it give you remain days. You can Also follow this Click Here

Categories

Resources