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.
Related
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);
}
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);
I am using DatePickerDialog to show the calender. I want to access First day and last day of the week of the date selected.
Here is what I have tried
this.tv_date.setText( new StringBuilder()
// Month is 0 based so add 1
.append(mDay).append("-")
.append(monthName).append("-")
.append(mYear).append(""));
tv_date.setHighlightColor(Color.CYAN);
String str=mDay+"-"+mMonth+"-"+mYear;
SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
sdf.format(""+str); //here I am getting exception
Calendar cal=Calendar.getInstance();
int s= cal.getFirstDayOfWeek();
Toast.makeText(getApplicationContext(), "first day of the week : "+s, 1).show();
But I am getting "IllegalArguementException".
Please help me
Thanks
sdf.format(""+str); - is wrong. You either need to pass a Date object to it, or else, change it to sdf.parse(str); to get a Date object from it.
Edit:- To get the first day of the week, do this.
String str=mDay+"-"+mMonth+"-"+mYear;
SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
Date myDate = new Date();
try{
myDate = sdf.parse(str);
}catch(ParseException pe){
// Do Something
}
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.set(Calendar.DAY_OF_WEEK, 1);
int s = cal.get(Calendar.DATE);
Here is an example of calculating the first day of week.
private void firstDayOfThisWeek(){
DateTime today = DateTime.today(TimeZone.getDefault());
DateTime firstDayThisWeek = today; //start value
int todaysWeekday = today.getWeekDay();
int SUNDAY = 1;
if(todaysWeekday > SUNDAY){
int numDaysFromSunday = todaysWeekday - SUNDAY;
firstDayThisWeek = today.minusDays(numDaysFromSunday);
}
System.out.println("The first day of this week is : " + firstDayThisWeek);
}
Instead of assigning today you can assign any other day with exact format
I am writing an application in which I have to display a date . Now I want to convert that date into Year and Month from the Current Date.
My Date is Like - 29/03/2017.
I want to convert this date into Year and Months.
Sorry I think you are not able to understand my question. I want the Difference of current date and above date in year and months.
Sorry for my explanation.
You can use Joda Time and compute a Period between two LocalDate values (which is what you've got here) using months and years as the units.
example
LocalDate dob = new LocalDate(1992, 12, 30);
LocalDate date = new LocalDate(2010, 12, 29);
Period period = new Period(dob, date, PeriodType.yearMonthDay());
System.out.println(period.getYears() + " years and " +
period.getMonths() + " months");
I found my answer using Calender class .
First i find the difference between two days and using that days i found the years and months.
Here i post my code, which i think help to others.
int days = Integer.parseInt(Utility.getDateDiffString("29/03/2017"));
int years = days/365;
int remainingDays = days - (365*years);
int months = remainingDays/30;
getDateDiffString() Method. In this method we need to pass end date
public static String getDateDiffString(String endDate)
{
try
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date dateTwo = dateFormat.parse(endDate);
long timeOne = cal.getTimeInMillis();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "" + delta + "";
}
else {
delta *= -1;
return "" + delta + "";
}
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
if your date's format is fixed, you can do it like this :
String myDate = "29/03/2017";
String newDate = myDate.subString(6, 10) + "-" + myDate.subString(3, 5)
this method to convert the normal string to date format
String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("mm/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);
after that you get the formal method
You Should use SimpleDateFormate !
For Example:--- You can get time & Date as you want:-
Date email_date = m.getSentDate();// this is date which you are getting
DateFormat date = new SimpleDateFormat("EEE MMM yyyy");
DateFormat time = new SimpleDateFormat("hh:mm aa");
String date_str=date.format(email_date);
String time_str=time.format(email_date);
Use Java Calendar class to get year from date
Calendar c=Calendar.getInstance();
SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy MMM");
System.out.println(simpleDateformat.format(c.getTime()));
To get difference between two date
int diffInDays = (int)( (newerDate.getTime() - olderDate.getTime())
/ (1000 * 60 * 60 * 24) )
long timeDiff = (d1.getTime() - d2.getTime());
String diff=String.format("%d year(s) %d day(s) %d hour(s) %d min(s) %d sec(s)",(TimeUnit.MILLISECONDS.toDays(timeDiff)/365),TimeUnit.MILLISECONDS.toDays(timeDiff)%365,
TimeUnit.MILLISECONDS.toHours(timeDiff)
- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS
.toDays(timeDiff)),
TimeUnit.MILLISECONDS.toMinutes(timeDiff)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(timeDiff)),
TimeUnit.MILLISECONDS.toSeconds(timeDiff)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(timeDiff)));
System.out.println(diff);
Specify correct date here in d1 & d2.Then you will get right answer of difference
First put your Date into a String variable as:
String dateToConvert = "29/03/2017";
Instantiate Calendar as:
Calendar convertedDate = Calendar.getInstance();
Set that date to calendar
convertedDate.set(dateToConvert);<br/>
Then use this line:
String datePicked = DateFormat.getDateInstance().format(convertedDate.getTime());
Output: Mar 29, 2017
This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 2 years ago.
I want to get the date as a year, month ,day without hours or minutes or any thing else, and I don't want to get the year alone and the month and the day each by its self. Because as a full date I need it to comparison with another date
such as today 28.11.2012 and to compare it to 11.12.2011
as if today minus 11.12.2011 more than 280 day I want to execute some code
you can use SimpleDateFormat.
The basics for getting the current date
DateFormat df = new SimpleDateFormat("MMM d, yyyy");
String now = df.format(new Date());
or
DateFormat df = new SimpleDateFormat("MM/dd/yy");
String now = df.format(new Date());
EDITED :
First of All you have the date in String Formate. you have to Convert into date Formate. try below code to do that. you have apply same for both the String strThatDay & strTodaDay you will get Calender Object for both.
String strThatDay = "2012/11/27";
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);
after that try below code to get Day from two Date :
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);
try it out. Hope it will help you.
Always use Simpledateformat(yyyy/mm/dd) for comparision..
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String currentDateandTime = sdf.format(new Date());
Use this currentDateandTime to compare with other date.
I think this may be a solution.U have to get instance of 2 calendar (1 for current date and another for compare date.
Calendar cal1=Calendar.getInstance();
Date dt=null;
try{
dt = sdf.parse(currentDateandTime);
cal1.setTime(dt);
}catch (ParseException e){
e.printStackTrace();
}
int currentDaycmp= cal1.get(Calendar.DAY_OF_MONTH);
int currentMonthcmp=cal1.get(Calendar.MONTH);
int currentYearcmp=cal1.get(Calendar.YEAR);
Calendar cal2=Calendar.getInstance();
Date dtend=null;
try{
dtend = sdf.parse(comparedate);
cal2.setTime(dtend);
} catch (ParseException e) {
e.printStackTrace();
}
int currentDayend= cal2.get(Calendar.DAY_OF_MONTH);
int currentMonend=cal2.get(Calendar.MONTH);
int currentyearend=cal2.get(Calendar.YEAR);
now find the difference
currentDaycmp-currentDayend(your condition)..then execute your block..
U try this..May be meet ur requirement..
You may want to use Joda-Time for this:
final DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy");
LocalDate first = LocalDate.parse("28.11.2012", formatter);
// LocalDate first = new LocalDate(2012, 11, 28);
// LocalDate first = LocalDate.now();
LocalDate second = LocalDate.parse("11.12.2011", formatter);
int daysBetween = Days.daysBetween(first, second).getDays();
You should be aware of that daysBetween is a negative value if the second date is before the first like in this example.
For the given example daysBetween is -353.
You can use the compareTo method.
Firstly, make sure that the two dates you are using have the same format. That is, if one is YYYY,DD,MM then the other would be the same.
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
Date firstDate = sdf.parse("2012-11-27");
System.out.println(sdf.format(firstDate));
And then you would do a firsDate.compareTo(SecondDate);
if firstDate.compareTo(SecondDate) < 280 {
...
}
Calendar todayCalendar = new GregorianCalendar();
Calendar pickedDateCalendar = new GregorianCalendar();
todayCalendar.set(currentYear,currentMonth,currentDay);
pickedDateCalendar.set(birthDayDatePicker.getYear(),birthDayDatePicker.getMonth(),birthDayDatePicker.getDayOfMonth());
System.out.println("Days= "+daysBetween(todayCalendar.getTime(),pickedDateCalendar.getTime()));
int Days = daysBetween(todayCalendar.getTime(),pickedDateCalendar.getTime());
public int daysBetween(Date d1, Date d2){
return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
}