This question already has answers here:
Date and calendar java
(2 answers)
Closed 5 years ago.
I have to compare two dates in if/else, the current date and the predefined date (let's say 1 Jan 2011). This was supposed to be simple, but I can't find the way to set the predefined date something like:
Java.util.Date date = new Date("2011-01-01");
How to compare two dates? I really don't know why it's so complicated to do.
Try:
import java.text.SimpleDateFormat;
import java.util.Date;
...
Date today = new Date();
Date predefined = new SimpleDateFormat("yyyy-MM-dd").parse("2011-01-01");
if(today.equals(predefined)) {
...
}
Use java.util.Calendar.
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, 2011);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DATE, 1);
Date predefined = cal.getTime();
Date now = new Date();
if (now.after(predefined))
{
// do something
}
else
{
// do something else
}
or use JodaTime.
How to compare two dates? I really don't know why it's so complicated to do.
Because calendars/dates/times are really hard to get right, and the Java implementation of Date (and, in part Calendar) is an utter train wreck.
date.CompareTo(someOtherDate);
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#compareTo(java.util.Date)
Related
This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
How to compare dates in Java? [duplicate]
(11 answers)
Closed 2 years ago.
How to compare two dates in Java by incrementing Date?
String dt = "2008-01-01"; // Start date
String et="2008-01-10";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date startDate=sdf.parse(dt);
Date endDate=sdf.parse(et);
Date incDate;
// dt is now the new date
do
{
System.out.println("hey i am called.....");
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime());
System.out.println("Incremet Date"+dt);
incDate=sdf.parse(dt);
}
while(endDate.compareTo(incDate)>=0);
first you should start using the newer classes like #TomStroemer pointed out.
I think you want to get the number of days between the two dates ?
LocalDate startDate = LocalDate.parse("2008-01-01");
LocalDate endDate = LocalDate.parse("2008-01-10");
Period period = Period.between(startDate, endDate);
System.out.println(period.getDays());
Should print 8 because there are 8 days between. Haven't tested that code.
See the following docs:
Period: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html
LocalDate: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
And really provide more details.
This question already has answers here:
Difference in days between two dates in Java?
(19 answers)
Closed 8 years ago.
i am trying to get the difference between two dates. one of the dates was parsed from a string(dateEmployd) and the other date is the current date (currentDate). This is what i did to get the dates...
public static Date getActiveService(String DtEmplydString){
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");//formater for parsed String date
Date dateEmployd, currentDate,periodDifference = null;
try{
dateEmployd = ft.parse(DtEmplydString);
currentDate = new Date();
}catch(ParseException e){
JOptionPane.showMessageDialog(null, e);
}
return periodDifference;
}
Now, i am meant to return periodDifference but i dont know how i would find the difference betweent the two dates (dateEmployd and currentDate) and display it in years or days or a combination of both.
please guys much help is needed. thanks in advance...
Take a look at the jodatime library. They have functions like
DateTime dateEmployd = DateTimeFormat.forPattern("yyyy-MM-dd").parse(DtEmplydString);
Years.yearsBetween(dateEmployd, DateTime.now())
The same for Days.daysbetween, Seconds, Hours etc.
long diff = date2.getTime() - date1.getTime();
You could try out the Java.Calendar for date functions because Date is deprecated .
Here is an example with Cdate comparators
Calendar start = Calendar.getInstance();
start.setTime(from ( your initial Date object here ) );
Calendar end = Calendar.getInstance();
end.setTime(new Date());
int actualDays = start.compareTo(end);
This question already has answers here:
Adding days to a date in Java [duplicate]
(6 answers)
Closed 8 years ago.
Below is the code which generates the output as "9/2/2014"
public static void main (String[]args) throws ParseException
{
java.util.Date d = new Date();
SimpleDateFormat sd = new SimpleDateFormat("M/d/yyyy");
System.out.println(sd.format(d));
}
Now i need to add some n no of days and i wanted to get the output as 9/12/2014
please help me ...
If you want add month, or days to your date, use something like that:
public static Date addDays(Date date, int days)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); //minus number would decrement the days
return cal.getTime();
}
to add month use Calendar.Month
Calendar has methods for date manipulations. First create Calendar instance and set date to it
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Then you can use calendar instance to add days like
calendar.add(Calendar.DATE,10);
to get date from calendar, use
System.out.println(calendar.getTime());
This question already has answers here:
How to get the date 7 days earlier date from current date in Java [duplicate]
(6 answers)
Closed 8 years ago.
I have today's date in this string format 2014-05-08 and I needed to get the date of 2 weeks prior the currents date.
So the data I should be getting back is - 2014-04-24.
String currentDate= dateFormat.format(date); //2014-05-08
String dateBefore2Weeks = currentDate- 2 week;
But I am not sure how do I extract date of two weeks prior to current date in Java?
Use Calendar to modify your Date object:
//method created for demonstration purposes
public Date getDateBeforeTwoWeeks(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -14); //2 weeks
return calendar.getTime();
}
Use the method above in your code:
String currentDate= dateFormat.format(date); //2014-05-08
String dateBefore2Weeks = dateFormat.format(getDateBeforeTwoWeeks(date));
Java now has a pretty good built-in date library, java.time bundled with Java 8.
import java.time.LocalDate;
public class Foo {
public static void main(String[] args) {
System.out.println(LocalDate.parse("2014-05-08").minusWeeks(2));
// prints "2014-04-24"
}
}
Parse the date using a SimpleDateFormat into a Date object
Use a Calendar object to subtract 14 days from that date
Format the resulting date using the same SimpleDateFormat
worth having a look into joda-time api [http://joda-time.sourceforge.net/userguide.html].
Let's say I have this:
PrintStream out = System.out;
Scanner in = new Scanner(System.in);
out.print("Enter a number ... ");
int n = in.nextInt();
I have a random date, for example, 05/06/2015 (it is not a fixed date, it is random every time). If I want to take the 'year' of the this date, and add whatever 'n' is to this year, how do i do that?
None of the methods in the Date Class are 'int'.
And to add years from an int, 'years' has to be an int as well.
You need to convert the Date to a Calendar.
Calendar c = Calendar.getInstance();
c.setTime(randomDate);
c.add(Calendar.YEAR, n);
newDate = c.getTime();
You can manipulate the Year (or other fields) as a Calendar, then convert it back to a Date.
This question has long deserved a modern answer. And even more so after Add 10 years to current date in Java 8 has been deemed a duplicate of this question.
The other answers were fine answers in 2012. The years have moved on, today I believe that no one should use the now outdated classes Calendar and Date, not to mention SimpleDateFormat. The modern Java date and time API is so much nicer to work with.
Using the example from that duplicate question, first we need
private static final DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
With this we can do:
String currentDateString = "2017-09-12 00:00:00";
LocalDateTime dateTime = LocalDateTime.parse(currentDateString, formatter);
dateTime = dateTime.plusYears(10);
String tenYearsAfterString = dateTime.format(formatter);
System.out.println(tenYearsAfterString);
This prints:
2027-09-12 00:00:00
If you don’t need the time of day, I recommend the LocalDate class instead of LocalDateTime since it is exactly a date without time of day.
LocalDate date = dateTime.toLocalDate();
date = date.plusYears(10);
The result is a date of 2027-09-12.
Question: where can I learn to use the modern API?
You may start with the Oracle tutorial. There’s much more material on the net, go search.
Another package for doing this exists in org.apache.commons.lang3.time, DateUtils.
Date date = new Date();
date = DateUtils.addYears(date, int quantity = 1);
The Date class will not help you, but the Calendar class can:
Calendar cal = Calendar.getInstance();
Date f;
...
cal.setTime(f);
cal.add(Calendar.YEAR, n); // Where n is int
f = cal.getTime();
Notice that you still have to assign a value to the f variable. I frequently use SimpleDateFormat to convert strings to dates.
Hope this helps you.
Try java.util.Calendar type.
Calendar cal=Calendar.getInstance();
cal.setTime(yourDate.getTime());
cal.set(Calendar.YEAR,n);
This will add 3 years to the current date and print the year.
System.out.println(LocalDate.now().plusYears(3).getYear());
If you need add one year a any date use the object Calendar.
Calendar dateMoreOneYear = Calendar.getInstance();
dateMoreOneYear.setTime(dateOriginal);
dateMoreOneYear.add(Calendar.DAY_OF_MONTH, 365);
Try like this as well for a just month and year like (June 2019)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, n); //here n is no.of year you want to increase
SimpleDateFormat format1 = new SimpleDateFormat("MMM YYYY");
System.out.println(cal.getTime());
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
Try this....
String s = new SimpleDateFormat("YYYY").format(new Date(random_date_in_long)); //
int i = Integer.parseInt(s)+n;