To find wednesday between to dates given by the user - java

I need to find wednesday for the two dates given by the user.
example:
Inputs are:
from date:07-Feb-2013
To date:13-feb-2013
The gap between the from date and To date is 7 days always.
Expected Output:12-feb-2013
public String getAutoDayExpiryDateAndToDate(String instrmentId,String deliveryAutoFromDate)
throws SystemException, FunctionalException,ParseException
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(deliveryAutoFromDate));
Date fromDate=calendar.getTime();
SimpleDateFormat sf1 = new SimpleDateFormat("dd-MMM-yyyy");
String formatedDate = sf1.format(fromDate);
calendar.add(Calendar.WEEK_OF_MONTH, 1);
calendar.add(Calendar.DAY_OF_WEEK,-1);
Date time = calendar.getTime();
SimpleDateFormat sf = new SimpleDateFormat("dd-MMM-yyyy");
String formatedDate1 = sf.format(time);
}
after these i need to find Wednesday which is present between formatedDate and formatedDate1 .how can i do it??

Use the Calendar class. Set it to the first date, and then check if the current day of the week is Wednesday by calling calendar.get(Calendar.DAY_OF_WEEK). Perform this check in a loop, adding a day to the current date during each iteration. This will never take more than seven steps, so you don't need to do anything fancier than that.

this should find the first Wednesday after (or equal) the given date
GregorianCalendar c = new GregorianCalendar(2013, 1, 7);
if (c.get(Calendar.DAY_OF_WEEK) <= Calendar.WEDNESDAY) {
c.add(Calendar.DAY_OF_YEAR, Calendar.WEDNESDAY - c.get(Calendar.DAY_OF_WEEK));
} else {
c.add(Calendar.DAY_OF_YEAR, 11 - c.get(Calendar.DAY_OF_WEEK));
}
System.out.println(c.getTime());
prints
Wed Feb 13 00:00:00 EET 2013
you can test it to see if it gives you what you want

Related

How to check if the given time falls in mentioned time range

I want to check if my Date value from -
Date d = convertCurrentTimeToSpecificTimeZone("America/Chicago", 2, 30);
falls in the range of 10am to 6 pm.
I found some similar links on StackOverflow similar question and used some of the code from this thread.
All I want to check if the current time from any timezone falls under the range of 10 am to 6 pm. If Yes, print "yes" else print "no".
Currently for below code:
String string1 = "10:11:13";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
System.out.println(calendar1.getTime().toString());
It just prints the 10:11 am time of 1970 year. Like this - Fri Jan 02 10:11:13 IST 1970.
But I want to check if today's or any future date time falls in the range of 10 am to 6pm.
Below is the code reference:
public static Date convertCurrentTimeToSpecificTimeZone(String timeZone, int increaseDateBy,
int increaseMinutesBy) {
Calendar calendar = Calendar.getInstance();
TimeZone fromTimeZone = calendar.getTimeZone();
TimeZone toTimeZone = TimeZone.getTimeZone(timeZone);
calendar.setTimeZone(fromTimeZone);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
increaseCalenderDateBy(calendar, increaseDateBy);
increaseCalenderMinuteBy(calendar, increaseMinutesBy);
return calendar.getTime();
}
public static void getTimeBetweenRange() throws ParseException {
String string1 = "10:11:13";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
System.out.println(calendar1.getTime().toString());
String string2 = "18:49:00";
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
System.out.println(calendar2.getTime().toString());
Date d = convertCurrentTimeToSpecificTimeZone("America/Chicago", 2, 30);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
System.out.println(calendar3.getTime().toString());
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
// checkes whether the current time is between 14:49:00 and 20:11:13.
System.out.println(true);
} else
System.out.println(false);
}
So the output for my below code is:
Fri Jan 02 10:11:13 IST 1970
Fri Jan 02 18:49:00 IST 1970
Fri Jan 31 03:15:07 IST 2020
It’s not very clear. For this answer I am assuming that all of your times are to be understood in America/Chicago time zone. Please revert if this was not what you intended.
java.time
ZoneId zone = ZoneId.of("America/Chicago");
ZonedDateTime zdt = ZonedDateTime.now(zone).plusDays(2).plusMinutes(30);
LocalTime rangeStart = LocalTime.parse("10:11:13");
LocalTime rangeEnd = LocalTime.parse("18:49:00");
LocalTime time = zdt.toLocalTime();
if (!time.isBefore(rangeStart) && time.isBefore(rangeEnd)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
When I ran this code snippet just now (at 11:30 Chicago time), the output was:
Yes
I am using java.time, the modern Java date and time API, and recommend that you do the same. It’s so much nicer to work with than the old, outdated and poorly designed classes Date, SimpleDateFormat, Calendar and TimeZone.
A LocalTime is a time of day from 00:00 (inclusive) to 24:00 (exclusive). By comparing LocalTimeobjects we are ignoring the date and have no trouble with irrelevant dates in 1970 or some other time in history.
Edit:
Also is it possible to get the date and time of rangeStart and
rangeEnd in order to verify for which particular day and time we are
checking the conditions?
No, that would not make sense. Since a LocalTime is a time of day without date, there is no way to get a date out of it. But you can print the ZonedDateTime and verify its date part. And to assure yourself that the code is correct, write some unit tests.
Link: Oracle tutorial: Date Time explaining how to use java.time.
A simple approach might be to parse your time Strings to instances of LocalTime and compare them. You have to decide if the start and end time are inclusive or not...
Support some formattings because you might have to pass Strings with AM/PM or without:
public static boolean isInTimeSlot(String time, String timeSlotStart, String timeSlotEnd) {
// create a formatter that supports different formats for the String arguments
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("[hh:mm:ss a][HH:mm:ss][h a]");
// parse each argument to a LocalTime
LocalTime timeOfDay = LocalTime.parse(time, parserDtf);
LocalTime fromTime = LocalTime.parse(timeSlotStart, parserDtf);
LocalTime toTime = LocalTime.parse(timeSlotEnd, parserDtf);
// and return if the given time is in the time slot (including start and end time)
return timeOfDay.equals(fromTime) || timeOfDay.equals(toTime)
|| (timeOfDay.isAfter(fromTime) && timeOfDay.isBefore(toTime));
}
If you run it in a main like this
public static void main(String[] args) {
// provide some sample times
String[] times = { "10:31:17", "09:59:59", "6 PM", "4 AM", "06:00:01 PM" };
// provide a time slot
String from = "10 AM";
String to = "6 PM";
// check the method for each time string
for (String time : times) {
if (isInTimeSlot(time, from, to)) {
System.out.println(time + " is in the time slot at or between "
+ from + " and " + to);
} else {
System.err.println(time + " is not in the time slot at or between "
+ from + " and " + to);
}
}
}
the output will be
10:31:17 is in the time slot at or between 10 AM and 6 PM
09:59:59 is not in the time slot at or between 10 AM and 6 PM
6 PM is in the time slot at or between 10 AM and 6 PM
4 AM is not in the time slot at or between 10 AM and 6 PM
06:00:01 PM is not in the time slot at or between 10 AM and 6 PM
All I want to check if the current time from any timezone falls under the range of 10 am to 6 pm. If Yes, print "yes" else print "no".
For this, the following code will do the job.
LocalTime lt = LocalTime.now();
if( lt.isAfter( LocalTime.of( 10, 0 ) ) && lt.isBefore( LocalTime.of( 18, 0 ) ) ) System.out.println( "Yes" );
else System.out.println( "No" );
Since you have Date instances with you, you can convert them into LocalTime instances as shown below and use the same mechanism of comparison.
Date d = new Date(); //Change this to your way of creating the Date instance
LocalTime lt = LocalDateTime.ofEpochSecond( d.getTime(), 0, ZoneOffset.ofHours( 0 ) ).toLocalTime();
Hope this helps.

Is there a built in function (Java) for an Android app to get the date range of the week of the current date ("today") [duplicate]

I want to get the last and the first week of a week for a given date.
e.g if the date is 12th October 2011 then I need the dates 10th October 2011 (as the starting date of the week) and 16th october 2011 (as the end date of the week)
Does anyone know how to get these 2 dates using the calender class (java.util.Calendar)
thanks a lot!
Some code how to do it with the Calendar object. I should also mention joda time library as it can help you many of Date/Calendar problems.
Code
public static void main(String[] args) {
// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);
// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK,
first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);
// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " +
df.format(last.getTime()));
}
This solution works for any locale (first day of week could be Sunday or Monday).
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
Date weekStart = c.getTime();
// we do not need the same day a week after, that's why use 6, not 7
c.add(Calendar.DAY_OF_MONTH, 6);
Date weekEnd = c.getTime();
For example, today is Jan, 29 2014. For the locale with Sunday as a first day of week you will get:
start: 2014-01-26
end: 2014-02-01
For the locale with Monday as a first day the dates will be:
start: 2014-01-27
end: 2014-02-02
If you want all dates then
first.add(Calendar.DAY_OF_WEEK,first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
for (int i = 1; i <= 7; i++) {
System.out.println( i+" Day Of that Week is",""+first.getTime());
first.add(Calendar.DAY_OF_WEEK,1);
}
Here is the sample code
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2016, 2, 15);
{
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = startCal.get(Calendar.DAY_OF_WEEK);
startCal.set(Calendar.DAY_OF_MONTH,
(startCal.get(Calendar.DAY_OF_MONTH) - dayOfWeek) + 1);
System.out.println("end date : " + startCal.getTime());
}
{
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = endCal.get(Calendar.DAY_OF_WEEK);
endCal.set(Calendar.DAY_OF_MONTH, endCal.get(Calendar.DAY_OF_MONTH)
+ (7 - dayOfWeek));
System.out.println("start date : " + endCal.getTime());
}
}
which will print
start date : Sun Mar 13 20:30:30 IST 2016
end date : Sat Mar 19 20:30:30 IST 2016
I have found the formula in the accepted answer will only work in some cases. For example your week starts on Saturday and today is Sunday. To arrive at the first day of the week we walk back 1 day, but the formula cal.get(Calendar.DAY_OF_WEEK) - cal.getFirstDayOfWeek() will give the answer -6. The solution is to use a modulus so the formula wraps around so to speak.
int daysToMoveToStartOfWeek = (
7 +
cal.get(Calendar.DAY_OF_WEEK) -
cal.getFirstDayOfWeek()
)%7;
cal.add(Calendar.DAY_OF_WEEK, -1 * daysToMoveToStartOfWeek);

difference between two dates in java in 'EST' time zone

I have to parse a string to a date, let us say givenDate, to EST timezone.
Also, I have to take the current date, let us say currentDate in EST timezone.
My current timezone is IST (GMT+5:30).
If the currentDate is greater than givenDate then I need to add a day to currentDate.
Here is the solution that I have implemented.
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Calendar givenDate = Calendar.getInstance(TimeZone.getTimeZone("EST"));
givenDate .setTime(df.parse("01/08/2016"));
Calendar currentDate = Calendar.getInstance(TimeZone.getTimeZone("EST"));
if(currentDate.get(Calendar.YEAR) > givenDate .get(Calendar.YEAR) ||
currentDate.get(Calendar.DAY_OF_YEAR) > givenDate.get(Calendar.DAY_OF_YEAR)){
currentDate.add(Calendar.DATE, 1);
}
System.out.println("Final date : "+df.format(currentDate.getTime()));
Is there any better solution for this?
Also, the following has been tickling my mind.
Consider code snippet
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Calendar givenDate = Calendar.getInstance(TimeZone.getTimeZone("EST"));
givenDate .setTime(df.parse("01/07/2016"));
System.out.println(givenDate .get(Calendar.DATE)); //6
System.out.println(givenDate .get(Calendar.DAY_OF_MONTH)); //6
System.out.println(givenDate .get(Calendar.DAY_OF_YEAR)); //6
Why am I getting 6 for DATE, DAY_OF_MONTH, DAY_OF_YEAR? I would expect
they must return 7 as the given date is 7 days from the starting of
the year 2016.
But if I add the following line after first line of above code, above mentioned fields are returning 7. What could be the reason of this?
df.setTimeZone(TimeZone.getTimeZone("EST"));
.
You need to set the timezone into the SimpleDateFormat class, and then you can compare the parsed Date with the current time:
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
df.setTimeZone(TimeZone.getTimeZone("EST"));
Date givenDate = df.parse("01/08/2016");
Calendar currentDate = Calendar.getInstance();
if(currentDate.getTime().compareTo(givenDate) > 0) {
currentTime.add(Calendar.DATE, 1);
}
Keep in mind that a Date object represents the current time (number of seconds since epoch) in UTC timezone.

Getting the start and the end date of a week using java calendar class

I want to get the last and the first week of a week for a given date.
e.g if the date is 12th October 2011 then I need the dates 10th October 2011 (as the starting date of the week) and 16th october 2011 (as the end date of the week)
Does anyone know how to get these 2 dates using the calender class (java.util.Calendar)
thanks a lot!
Some code how to do it with the Calendar object. I should also mention joda time library as it can help you many of Date/Calendar problems.
Code
public static void main(String[] args) {
// set the date
Calendar cal = Calendar.getInstance();
cal.set(2011, 10 - 1, 12);
// "calculate" the start date of the week
Calendar first = (Calendar) cal.clone();
first.add(Calendar.DAY_OF_WEEK,
first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
// and add six days to the end date
Calendar last = (Calendar) first.clone();
last.add(Calendar.DAY_OF_YEAR, 6);
// print the result
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(first.getTime()) + " -> " +
df.format(last.getTime()));
}
This solution works for any locale (first day of week could be Sunday or Monday).
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);
Date weekStart = c.getTime();
// we do not need the same day a week after, that's why use 6, not 7
c.add(Calendar.DAY_OF_MONTH, 6);
Date weekEnd = c.getTime();
For example, today is Jan, 29 2014. For the locale with Sunday as a first day of week you will get:
start: 2014-01-26
end: 2014-02-01
For the locale with Monday as a first day the dates will be:
start: 2014-01-27
end: 2014-02-02
If you want all dates then
first.add(Calendar.DAY_OF_WEEK,first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));
for (int i = 1; i <= 7; i++) {
System.out.println( i+" Day Of that Week is",""+first.getTime());
first.add(Calendar.DAY_OF_WEEK,1);
}
Here is the sample code
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2016, 2, 15);
{
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = startCal.get(Calendar.DAY_OF_WEEK);
startCal.set(Calendar.DAY_OF_MONTH,
(startCal.get(Calendar.DAY_OF_MONTH) - dayOfWeek) + 1);
System.out.println("end date : " + startCal.getTime());
}
{
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(cal.getTimeInMillis());
int dayOfWeek = endCal.get(Calendar.DAY_OF_WEEK);
endCal.set(Calendar.DAY_OF_MONTH, endCal.get(Calendar.DAY_OF_MONTH)
+ (7 - dayOfWeek));
System.out.println("start date : " + endCal.getTime());
}
}
which will print
start date : Sun Mar 13 20:30:30 IST 2016
end date : Sat Mar 19 20:30:30 IST 2016
I have found the formula in the accepted answer will only work in some cases. For example your week starts on Saturday and today is Sunday. To arrive at the first day of the week we walk back 1 day, but the formula cal.get(Calendar.DAY_OF_WEEK) - cal.getFirstDayOfWeek() will give the answer -6. The solution is to use a modulus so the formula wraps around so to speak.
int daysToMoveToStartOfWeek = (
7 +
cal.get(Calendar.DAY_OF_WEEK) -
cal.getFirstDayOfWeek()
)%7;
cal.add(Calendar.DAY_OF_WEEK, -1 * daysToMoveToStartOfWeek);

Get Previous Day [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
How to determine the date one day prior to a given date in Java?
If I have a Java.Util.Date object, what is the best way to get an object representing the 24 hours in the past of it?
Using Java 1.6 java.util.Calendar.add:
public static Date subtractDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
Others suggest using Joda Time, which is currently JSR 310, and should later be included in Java itself.
The important thing to remember is that the Date class should represent any points in time whilst the Calendar class is used to manipulate those points in time. Last of all, SimpleDateFormat will represent them as Strings.
So, the best way is to use the Calendar class to calculate the new Date for you. This will ensure that any vagaries (Daylight Saving, Leap Years and the like) are accounted for.
I'm assuming that you don't really want to find '24 Hours previous' but actually do want a new Date instance representing 'this time yesterday' - either way, you can ask the Calendar instance for a Date 24Hours prior to another or 1 Day prior.
The Daylight savings is a great example. The UK 'sprang forward' on the 26th March 2009. So, 1 day prior to 3.00a.m. on the 26.Mar.2009 should yield 3.00a.m. 25.Mar.2009 but 24 Hrs prior will yield 2.00a.m.
public class DateTests extends TestCase {
private static String EXPECTED_SUMMER_TIME = "2009.Mar.29 03:00:00";
private static String EXPECTED_SUMMER_TIME_LESS_DAY = "2009.Mar.28 03:00:00";
private static String EXPECTED_SUMMER_TIME_LESS_24_HRS = "2009.Mar.28 02:00:00";
private static String EXPECTED_SUMMER_TIME_LESS_FURTHER_24_HRS = "2009.Mar.27 02:00:00";
public void testSubtractDayOr24Hours() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MMM.dd HH:mm:SS");
Calendar calendar = Calendar.getInstance();
// Create our reference date, 3.00 a.m. on the day the clocks go forward (they 'went' forward at 02.00)
calendar.clear();
calendar.set(2009, 2, 29, 3, 0);
Date summerTime = calendar.getTime(); // Sun Mar 29 03:00:00 BST 2009
String formattedSummerTime = formatter.format(summerTime);
calendar.add(Calendar.DAY_OF_MONTH, -1);
// Our reference date less 'a day'
Date summerTimeLessADay = calendar.getTime(); // Sat Mar 28 03:00:00 GMT 2009
String formattedSummerTimeLessADay = formatter.format(summerTimeLessADay);
// reset the calendar instance to the reference day
calendar.setTime(summerTime);
// Our reference date less '24 hours' (is not quite 24 hours)
calendar.add(Calendar.HOUR, -24);
Date summerTimeLess24Hrs = calendar.getTime(); // Sat Mar 28 02:00:00 GMT 2009
String formattedSummerTimeLess24Hrs = formatter.format(summerTimeLess24Hrs);
// Third date shows that taking a further 24 hours from yields expected result
calendar.add(Calendar.HOUR, -24);
Date summerTimeLessFurther24Hrs = calendar.getTime(); // Fri Mar 27 02:00:00 GMT 2009
String formattedSummerTimeLessFurther24Hrs = formatter.format(summerTimeLessFurther24Hrs);
// reset the calendar once more to the day before
calendar.setTime(summerTimeLess24Hrs);
// Take a 'day' from the Sat will yield the same result as date 03 because Daylight Saving is not a factor
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date summerTimeLessFurtherDay = calendar.getTime(); // Fri Mar 27 02:00:00 GMT 2009
String formattedSummerTimeLessFurtherDay = formatter.format(summerTimeLessFurtherDay);
assert(formattedSummerTime.equals(EXPECTED_SUMMER_TIME));
assert(formattedSummerTimeLessADay.equals(EXPECTED_SUMMER_TIME_LESS_DAY));
assert(formattedSummerTimeLess24Hrs.equals(EXPECTED_SUMMER_TIME_LESS_24_HRS));
assert(formattedSummerTimeLessFurther24Hrs.equals(EXPECTED_SUMMER_TIME_LESS_FURTHER_24_HRS));
// This last test proves that taking 24 hors vs. A Day usually yields the same result
assert(formattedSummerTimeLessFurther24Hrs.equals(formattedSummerTimeLessFurtherDay));
}
}
For testing date functions, wwwdot-timeanddate-dot-com is a great resource.
subtract 1000*60*60*24 from the time and create a new date.
Date yesterday = new Date(d.getTime() - (1000*60*60*24));
int dayInMs = 1000 * 60 * 60 * 24;
Date previousDay = new Date(olddate.getTime() - dayInMs);
Personally if there are a lot of time/date calculations, I'd go with Joda-time.

Categories