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));
}
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 calculating time difference between two dates and time but its restuning invalid difference.
here's my sample date and code to calculate the difference.
loginTime=2016-01-24 12:04:30.16
expiryTime = 2016-01-24 13:04:30.16
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date now = new Date();
try {
Date startDate = simpleDateFormat.parse(loginTime);
Date expireDate = simpleDateFormat.parse(expiryTime);
// String temCurrentDate = new SimpleDateFormat("yyyy-MM-dd").format(now);
// Date currentDate = new SimpleDateFormat("yyyy-MM-dd").parse(temCurrentDate);
// String day_of_week = new SimpleDateFormat("EEEE").format(now);
long difference =startDate.getTime()- expireDate.getTime();
int hour = (int) difference / (60 * 60 * 1000);
} catch (ParseException e) {
e.printStackTrace();
}
Difference between this time is 1 hour but i am getting 11 or 13. Please tell where i am going wrong in this.
Spelling error in your variable:
simpleDateFormat.parse(expiryTime);
Does not match: ExpiryTime = 2016-01-24 13:04:30.16
That's the whole problem.
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.
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
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