java Date object- how to increment day of week [duplicate] - java

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).

Related

java pass in string date and get the days different from current date

I am doing up a script where by the user will pass in string date (MM/DD/YYYY). I want to compare this string date to the "today" date to find out the days different between these 2 days.
This is my codes to get "today" date.
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
returnDate = dateFormat.format(cal.getTime());
How do i go about using date to minus date? convert them to timestamp and convert it back?
Thank you
getTimeInMillis() and the relevant division will tell you how many days different. Not sure why converting it back is helpful.
If you can use JodaTime library. A similar question with usage of this library was already answered here.
In this first i get the current date and then minus by 2 then using formatter and set the same accordingly. So the ouput you will get will be 2 days before todays date, Please try below:-
Calendar cal=Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -2);
Date dt=cal.getTime();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
String ss=format.format(dt);
System.out.println(ss);

Iterate through date ranges without using libraries - Java

Hi I want to iterate through a date range without using any libraries. I want to start on 18/01/2005(want to format it to yyyy/M/d) and iterate in day intervals until the current date. I have formatted the start date, but I dont know how I can add it to a calendar object and iterate. I was wondering if anyone can help. Thanks
String newstr = "2005/01/18";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/M/d");
Date date = format1.parse(newstr);
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
while (someCondition(calendar)) {
doSomethingWithTheCalendar(calendar);
calendar.add(Calendar.DATE, 1);
}
Use SimpleDateFormat to parse a string into a Date object or format a Date object into a string.
Use class Calendar for date arithmetic. It has an add method to advance the calendar, for example with a day.
See the API documentation of the classes mentioned above.
Alternatively, use the Joda Time library, which makes these things easier. (The Date and Calendar classes in the standard Java API have a number of design issues and are not as powerful as Joda Time).

Update time only

Is there any way to update only a Date's time path?
I tried Date.setTime() but it replaces the date path too. I there any java method or the only way is to set hour, minute, second and milisecond?
Thank you
A Java Date is just a wrapper around a long that counts time from the epoch (January 1, 1970). Much more flexible is Calendar. You can create a Calendar from a Date:
Date date = . . .;
Calendar cal = new GregorianCalendar();
cal.setTime(date);
Then you can set various fields of the Calendar:
cal.set(Calendar.HOUR_OF_DAY, 8);
// etc.
I would start by moving away from java.util.Date entirely. Ideally, use Joda Time as it's a far more capable date/time library.
Otherwise, you should use java.util.Calendar. A java.util.Date doesn't have a particular date/time until you decide what time zone you're interested in - it just represents an instant in time, which different people around the world will consider to be a different date and time of day.
You'll want to take a look at java.util.Calender.
It will allow you to change the individual parts of the date/time.
Calendar cal = Calender.getInstance();
cal.setTime(date);
cal.set(Calender.HOUR, hour);
Alternatively, as has already being suggested, I'd take a look at Joda Time

What's the right way to create a date in Java? [duplicate]

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.

Get Date as of 4 hours ago [duplicate]

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

Categories

Resources