This question already has answers here:
Why is the Date constructor deprecated, and what do I use instead?
(14 answers)
Closed 7 years ago.
The constructor java.util.Date(int,int,int) is deprecated. Is there a way to set a date easy as that in Java? What's the non-deprecated way to do this?
Date date = new Date(2015, 3, 2);
What's the non-deprecated way to do this?
Java 8 to the rescue:
LocalDate localDate = LocalDate.of(2015, 3, 2);
And then if you really really need a java.util.Date, you can use the suggestions in this question.
For more info, check out the API or the tutorials for Java 8.
By using
java.util.Calendar
is one possibility:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2015);
calendar.set(Calendar.MONTH, 4);
calendar.set(Calendar.DATE, 28);
Date date = calendar.getTime();
Keep in mind that months are 0 based, so January is 0-th month and december 11th.
Try Calendar.
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
I am sure there also is a method which takes the values you provide in your example.
Use the Calendar class, specifically the set(int year, int month, int date) for your purpose. This is from Java 7, but you'll have equivalent - setDate(), setYear() etc. - methods in older versions.
Related
This question already has answers here:
How can I find the number of days between two Dates?
(5 answers)
Closed 6 years ago.
Problem: Getting the difference in calendar days between two dates. For an example, 6/28/1996 23:59 is one day difference from 6/29/1996 12:00.
Research: I did a bunch of research online and everyone seems to only give the difference in milliseconds, which gives you the true difference in times, but not in calendar days.
Current Solution
(int) ((new java.sql.Date(System.currentTimeMillis()).getTime()/day_conversion)) - (int) (rs.getDate("attempt_time").getTime()/day_conversion) > 0
I did an int cast to the time of the date converted to days (thereby dropping any decimals) to both the current time and recorded time and took the difference. This left me with the actual conversion in calendar days; however, I was wondering if there is just a single written method that does this for me already.
Since Java 8 there exists the java.time API, superseding java.util.Date and related classes and providing a very clean way of solving your problem:
LocalDateTime date1 = LocalDateTime.of(1996, 6, 28, 23, 59);
LocalDateTime date2 = LocalDateTime.of(1996, 6, 29, 12, 59);
Period difference = Period.between(date1.toLocalDate(), date2.toLocalDate());
System.out.println(difference.getDays());
This is another way to compute difference between years. You can add the rest of date very easily.
Calendar c = Calendar.getInstance();
int y = c.get(Calendar.YEAR);
Calendar c2 = Calendar.getInstance();
c2.set(Calendar.YEAR, 2013);
int com = c.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
System.out.println(com);
This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 7 years ago.
I am currently trying to schedule a method for execution once per week on a day which the user will select. I know I can get the current date via:
Date date = new Date();
When setting up my TimerTask for execution, I need to increment the date by 1-6 days depending on which day of week is selected by the user. I do not see a setDay() method in the documentation and was wondering if parsing the day out, changing it, and adding back to the date object is the only way. Seems like something much more simple would be out there.
You need to use a Calendar.
The java.util.Calendar class is an abstract encapsulation of the Date object.
Calendar provides getter and setter for the date fields.
Updated to an example of incrementing the day of the week as requested:
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK,(calendar.get(Calendar.DAY_OF_WEEK)+1));
//alternative:
//calendar.add(Calendar.DAY_OF_WEEK, 1);
Date newDate = calendar.getTime();
Update: Note the java 8+ implementation using java.time
Calendar and Date have not been deprecated, you can still mix and match.
However if you want to handle time zones properly or want to do more localisation (when do you not?) then you are better off using java.time.
public static Date addDays(Date date, int days) {
GregorianCalendar calendar = getCalendar(date);
calendar.add(Calendar.DATE, days);
return calendar.getTime();
}
This should do the trick.
You probably want to use Calendar.
With a Calendar object, you can simply use Calendar.add(Calendar.DAY_OF_WEEK, 1); to add a single day
It would be easy with Calendar class.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1); // this will add number of days to current
// date
Date date = cal.getTime(); // it will return the date object
System.out.println(date);
You may be looking for Date.setDate().
Bear in mind that it's deprecated, and the docs recommend using Calendar.set(Calendar.DAY_OF_MONTH, int date).
This question already has answers here:
Why is January month 0 in Java Calendar?
(18 answers)
Closed 9 years ago.
I would like to understand why this happens, and how can i solve this small issue.
I would like to be able to get the week number from a java calendar instance after providing the day, the month and the year.
if i do:
Calendar cal=Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 11);
cal.set(Calendar.MONTH,2);
cal.set(Calendar.YEAR, 2013);
11 Feb 2013 is week 7, but if i invoke, in the above calendar instance:
int weekNumber=cal.get(Calendar.week_of_year)
I get the week number 11.
Any idea why?
I tried setting the locale but no difference, the problem is that i can only build a calendar out of these three fields, since i'm reading them from a xml file with a parser and they are in format dd-mm-yyyy with no more information that that
Months fields in Calendar are zero based. The value 2 corresponds to Calendar.MARCH. To avoid confusion, better to use the Calendar constants. You could use:
cal.set(Calendar.MONTH, Calendar.FEBRUARY);
You have used March, because Java months in Calendar are 0-based: 0 = January, 1 = February, 2 = March.
Use
cal.set(Calendar.MONTH,1);
or
cal.set(Calendar.MONTH, Calendar.FEBRUARY);
if you can use a constant. Else, subtract 1 from the month you received from your parser.
This question already has answers here:
Java Date vs Calendar
(13 answers)
Closed 8 years ago.
I get confused by the Java API for the Date class. Everything seems to be deprecated and links to the Calendar class. So I started using the Calendar objects to do what I would have liked to do with a Date, but intuitively it kind of bothers me to use a Calendar object when all I really want to do is create and compare two dates.
Is there a simple way to do that? For now I do
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day, hour, minute, second);
Date date = cal.getTime(); // get back a Date object
You can use SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");
But I don't know whether it should be considered more right than to use Calendar ...
The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:
DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);
You can try joda-time.
This question already has answers here:
How to create a Date object, using UTC, at a specific time in the past?
(2 answers)
Closed 5 years ago.
How can I return a Date object of 4 hours less than the current system time in Java?
If you're already on Java 8 or newer:
LocalDateTime fourHoursAgo = LocalDateTime.now().minusHours(4);
Or if you want to take DST (Daylight Saving Time) into account (just in case it coincidentally went into or out DST somewhere the last 4 hours):
ZonedDateTime fourHoursAgo = ZonedDateTime.now().minusHours(4);
Or if you're not on Java 8 yet:
Date fourHoursAgo = new Date(System.currentTimeMillis() - (4 * 60 * 60 * 1000));
And you want to take DST into account:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, -4);
Date fourHoursAgo = calendar.getTime();
The other answers are correct, but I would like to contribute the modern answer. The modern solution uses java.time, the modern Java date and time API.
Instant fourHoursAgo = Instant.now().minus(Duration.ofHours(4));
System.out.println(fourHoursAgo);
This just printed:
2018-01-31T15:22:21.113710Z
The Z in the end indicates that the time is printed in UTC — at UTC offset zero if you will. The Instant class is the modern replacement for Date, so I recommend you stick to it. The modern API is generally so much nicer to work with, so much cleaner, so much better designed.
Please note the advantages of letting the library class do the subtraction of 4 hours for you: the code is clearer to read and less error-prone. No funny constants, and no readers taking time to check if they are correct.
If you do need an old-fashioned Date object, for example when using a legacy API that you cannot change or don’t want to change, convert like this:
Date oldfashionedDate = Date.from(fourHoursAgo);
Link: Oracle Tutorial trail: Date Time. Of course there are other resources on the internet too, please search.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, -4);
calendar.getTime();
Convert it to milliseconds, subtract the number of milliseconds in 4 hours, convert it back to a Date.
Calendar c = Calendar.getInstance();
c.add(Calendar.HOUR_OF_DAY, -4);
java.util.Date d = c.getTime();
System.out.println(d);
Calendar c =Calendar.getInstance() ;
c.add(Calendar.HOUR,-4);
Date d = c.getTime();
Use a Calendar object and the add method.
calendar.add(Calendar.HOUR, -4);
See http://download.oracle.com/javase/6/docs/api/java/util/Calendar.html