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.
Related
there is a requirement to get the startTime and endTime around the whole year by giving a int year, for example, given a variable int year = 2017, I want to get the starttime String "2017-01-01 00:00:00" and endtime String "2017-12-31 23:59:59", or get the starttime timestamp 1483200000 and endtime timestamp 1514735999. 2 results are ok to us, How should I do by java8 or below? I have known:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String datetime = sdf.format(new Date(*timestamp*))
but I have no idea how I can get the timestamp by the given year, please help to check
int year = 2017;
// Using LocalDateTime (Java 8+ or Java 6+ with ThreeTen backport)
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
String start1 = LocalDateTime.of(year, Month.JANUARY, 1, 0, 0).format(dtf);
String stop1 = LocalDateTime.of(year, Month.DECEMBER, 31, 23, 59, 59).format(dtf);
System.out.println(start1 + " - " + stop1);
// Using Calendar (antiquated)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(year, Calendar.JANUARY, 1);
String start2 = sdf.format(cal.getTime());
cal.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
String stop2 = sdf.format(cal.getTime());
System.out.println(start2 + " - " + stop2);
Output
2017-01-01 00:00:00 - 2017-12-31 23:59:59
2017-01-01 00:00:00 - 2017-12-31 23:59:59
Use a half-open interval
As Basil Bourque said in a comment: use a half-open interval. That is, define year 2017 as the time from the first moment of 2017 inclusive to the first moment of 2018 exclusive. So any moment that is on or after the start time and strictly before the end time belongs to the year.
Philosophical argument: It saves us from deciding whether to run up to the last second, the last millisecond or the last nanosecond of the year. An even if we rook the last nano, we would still have excluded a full nano from the year, which is incorrect. Yes, I know, your application only needs a granularity of seconds, so “it doesn’t matter”. But what if the next version does require a finer granularity? And even if it won’t, you should not want to fill errors or inaccuracies into your program, not even when the user doesn’t see any symptom of them.
Practical argument: A half-open interval simplifies some things, both when calculating the timestamps and when applying them.
ZoneId zone = ZoneId.of("Asia/Singapore");
Year year = Year.of(2017);
long startTime = year.atDay(1).atStartOfDay(zone).toEpochSecond();
System.out.println(startTime);
long endTime = year.plusYears(1).atDay(1).atStartOfDay(zone).toEpochSecond();
System.out.println(endTime);
Output from this snippet is:
1483200000
1514736000
If you absolutely insist, you may of course subtract 1 from the latter number.
Notice that using atStartOfDay() also saves us from assuming that the day begins at 00:00:00 and ends a second after 23:59:59. Funny time anomalies may cause this not to be the case. Such anomalies are in the time zone database and Java takes them into account when we just query the start of day in a time zone.
You can do like this using java.sql.Timestamp
import java.util.Date;
import java.sql.Timestamp;
public class Main
{
public static void main( String[] args )
{
Date date= new Date();
long time = date.getTime();
System.out.println("Time (Milliseconds): " + time);
Timestamp ts = new Timestamp(time);
System.out.println("Current Time Stamp: " + ts);
}
}
Using Java 8 only:
int year = 2017;
// using one of the predefined format from enum java.time.format.FormatStyle
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
LocalDateTime beginDate = LocalDateTime.of(year, Month.JANUARY, 1, 0, 0, 0);
LocalDateTime endDate = LocalDateTime.of(year, Month.DECEMBER, 31, 23, 59, 59);
String beginDateFormatted = beginDate.format(formatter);
String endDateFormatted = endDate.format(formatter);
long beginTimestamp = this.beginDate.toInstant(ZoneOffset.UTC).toEpochMilli();
long endTimestamp = this.endDate.toInstant(ZoneOffset.UTC).toEpochMilli();
Check working example here.
This question already has answers here:
Java: Date from unix timestamp
(11 answers)
Converting Long to Date in Java returns 1970
(12 answers)
android timestamp parsing gone wrong(always in 1970)
(4 answers)
Closed 3 years ago.
I want to convert 1574348400 value to date format using code:
public class Main {
public Main() {
long value = 1574348400;
String dateString = new SimpleDateFormat("EEEE dd MMMM, yyyy").format(new Date(value));
System.out.println("Formated time: " + dateString);
}
public static void main(String[] args) {
new Main();
}
}
I want to get the output as: Wednesday 20 November, 2019 but I'm getting Monday 19 January, 1970. How to get the current date not the 1970's date?
Parse your time (in seconds) using java.time, it provides a method for epoch seconds...
public static void main(String[] args) {
// your seconds
long seconds = 1574348400;
// same in millis
long millis = 1574348400000L;
// find out the zone of your system
ZoneId systemDefaultZoneId = ZoneId.systemDefault();
// or set a specific one
ZoneId utcZoneId = ZoneId.of("UTC");
// parse a ZonedDateTime of your system default time zone from the seconds
ZonedDateTime fromSecsSysDefZone = ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds),
systemDefaultZoneId);
// parse a ZonedDateTime of UTC from the seconds
ZonedDateTime fromSecsUtc = ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds),
utcZoneId);
// parse a ZonedDateTime of your system default time zone from the milliseconds
ZonedDateTime fromMillisSysDefZone = ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis),
systemDefaultZoneId);
// parse a ZonedDateTime of UTC from the milliseconds
ZonedDateTime fromMillisUtc = ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis),
utcZoneId);
// print the ones that were created using your default time zone
System.out.println("from seconds:\t"
+ fromSecsSysDefZone.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
System.out.println("from millis:\t"
+ fromMillisSysDefZone.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// print a check for equality
System.out.println("Both ZonedDateTimes are "
+ (fromSecsSysDefZone.equals(fromMillisSysDefZone) ? "equal" : "different"));
System.out.println("————————————————————————————————");
// print the ones that were created using UTC
System.out.println("from seconds:\t"
+ fromSecsUtc.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
System.out.println("from millis:\t"
+ fromMillisUtc.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// print a check for equality
System.out.println("Both ZonedDateTimes are "
+ (fromSecsUtc.equals(fromMillisUtc) ? "equal" : "different"));
}
The output produced by this code (on my system) is
from seconds: 2019-11-21T16:00:00+01:00[Europe/Berlin]
from millis: 2019-11-21T16:00:00+01:00[Europe/Berlin]
Both ZonedDateTimes are equal
————————————————————————————————
from seconds: 2019-11-21T15:00:00Z[UTC]
from millis: 2019-11-21T15:00:00Z[UTC]
Both ZonedDateTimes are equal
If you have to use Java 6 or 7, then you can use the ThreeTenBackport-Project on Github, which enables (most) functionality of java.time in those two older versions.
Its use is explained on a separate website.
Wrong value. Try:
long value = 1574348400000L;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class BasicWebCrawler {
public BasicWebCrawler() {
long value = 1574348400000L;
Date date = new Date(value);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, -1);
Date minusOne = cal.getTime();
String dateString = new SimpleDateFormat("EEEE dd MMMM, yyyy").format(minusOne);
System.out.println("Formated time: " + dateString);
}
public static void main(String[] args) {
new BasicWebCrawler();
}
}
output : Formated time: Wednesday 20 November, 2019
Your first issue is: You are using seconds instead of milliseconds, new Date(long) the value of long is in milliseconds.
See the Java 6 java.util.Date Documentation here
Your second issue is: When using Java 6 Date you need to know where the value in milliseconds was determined, if it's not in your timezone then you will need to make a conversion. Take the following code for example:
String zeroDateString = new SimpleDateFormat("EEEE dd MMMM, yyyy hh:mm").format(new Date(0));
System.out.println("Formated time -- zeroDateString = " + zeroDateString);
The output of new Date(0) in NYC, NY, USA will be Wednesday December 31, 1969 19:00 (the timezone of New-York City is EST which is GMT-05:00) while in Rome, Italy the output of the same code will be Thursday 01 January 1970 01:00 (the timezone of Rome, Italy is GMT+01:00)
If you need all your data to be according to GMT then you will need to make adjustment and/or calculation according to your timezone in relation to GMT.
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);
The below code what i am trying is working if the time what i am checking is before the first time i am comparing with.
if timeToCompare is after 6 PM its wroking good and if it lies between two time slots its working good but only if it 01:00:00 AM which is not in the time frame but still its going into if condition.
Please correct em where if going wrong.
String string1 = "07:00:00 AM";
Date time1 = new SimpleDateFormat("HH:mm:ss a").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
String string2 = "06:00:00 PM";
Date time2;
time2 = new SimpleDateFormat("HH:mm:ss a").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
String timeToCompare = "01:00:00 AM";
System.out.println(formattedDate);
Date d = new SimpleDateFormat("HH:mm:ss a").parse(timeToCompare);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
My timeToCompare but be in between string1 and string2
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("Hi from time between given slots");
}
1:00:00 AM is not in middle of those tow time's but still it is gogin into if condition and it is pritning "Hi from time between given slots"
You are adding a day to string 2 and string 3. Internally, Java is storing your times as the following:
> calendar1.getTime()
Thu Jan 01 07:00:00 CST 1970
> calendar2.getTime()
Fri Jan 02 06:00:00 CST 1970
> calendar3.getTime()
Fri Jan 02 01:00:00 CST 1970
So, your time range is bigger than you think it is!
Incorrect Parsing Pattern
You should be using lowercase hh for an hour value 1-12. The uppercase HH is for 24-hour clock 0-23.
java.time
You should be using the new java.time framework built into Java 8 and later. The old java.util.Date/.Calendar and SimpleDateFormat classes are notoriously troublesome.
The new framework includes a class for time-only values, LocalTime. This class has no date, and no time zone. Yet note how a time zone is required to determine the current time.
String string1 = "07:00:00 AM";
String string2 = "06:00:00 PM";
String string3 = "01:00:00 AM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "hh:mm:ss a" , Locale.ENGLISH );
LocalTime localTime1 = formatter.parse ( string1 , LocalTime :: from );
LocalTime localTime2 = formatter.parse ( string2 , LocalTime :: from );
LocalTime localTime3 = formatter.parse ( string3 , LocalTime :: from );
LocalTime now = LocalTime.now ( ZoneId.of ( "America/Montreal" ) );
These LocalTime objects have convenient isBefore, isAfter, and isEqual methods.
Boolean isFirstInputEarlierThanNow = localTime1.isBefore ( now );
The LocalTime class also implements the Comparable interface. So you can sort them as seen in this example code.
List<LocalTime> localTimes = Arrays.asList ( localTime1 , localTime2 , localTime3 , now );
Collections.sort ( localTimes );
LocalTime earliest = localTimes.get ( 0 ); // Index, meaning zero-based counting.
LocalTime latest = localTimes.get ( localTimes.size () - 1 ); // Index (zero-based counting), so subtract one.
Dump to console.
System.out.println ( "localTimes: " + localTimes );
System.out.println ( "isFirstInputEarlierThanNow: " + isFirstInputEarlierThanNow );
System.out.println ( "earliest: " + earliest + " … latest: " + latest );
When run.
localTimes: [01:00, 07:00, 18:00, 19:26:41.932]
isFirstInputEarlierThanNow: true
earliest: 01:00 … latest: 19:26:41.932
I tried to write a code which displays the days of the week for the last 10 dates.
Here's a part of the code:
Calendar cal = Calendar.getInstance();
for(int i=0; i<=9;i++) {
cal.add(Calendar.DATE, -i);
Date tday=cal.getTime();
SimpleDateFormat dy = new SimpleDateFormat("EEE");
String d9 = dy.format(tday);
System.out.println(d9);
}
Instead of showing all the last 10 days in an order it is displaying like this:
Thu
Wed
Mon
Fri
Mon
Wed
Thu
Thu
Wed
Mon
Fri
Where did I make the mistake?
try this.
boolean work = true;
int day = 0; // 0 = today, 1 = yesterday etc...
int subDay = 0; // subtract day
while (work){
Calendar cal = Calendar.getInstance(); // get current time
cal.add(Calendar.DAY_OF_WEEK, subDay); // subtract day
// working days are Mon, Tue, Wed, Thu, Fri. If we get saturdays or sundays, we want to skip that days,
// so we use if declaration
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
subDay--;
continue;
}
Date tday=cal.getTime();
SimpleDateFormat dy = new SimpleDateFormat("EEE");
String d9 = dy.format(tday);
System.out.println("Day: " + day + " - " + d9);
day ++;
subDay--;
if (day >= 10){work=false;} // here we declara how much day we want to go back, and we break loop.
}
Avoid j.u.Date
The first mistake was using the java.util.Date and .Calendar classes bundled with Java. They are notoriously troublesome. Avoid them.
Use a decent date-time library. In Java that means either:
Joda-Time
java.time package in Java 8 (inspired by Joda-Time)
Both have their pros and cons.
Both offer a LocalDate class, which you need to represent a date-only without any time-of-day portion.
Date-Time Versus Text
The Question’s code mixes date-time values with their String representations. Better to get your work done using date-time values. Afterwards, separately, create String representations for presentation to the user. The idea is a separation of concerns, to make your code more clear and easier to test/debug.
Joda-Time
Example code in Java-Time.
You will have to specify which days of the week are business days.
Note the use of a time zone. The current date depends on your position on the globe (the time zone). A new day dawns in Paris earlier than in Montréal. If you omit the time zone, the JVM’s default is applied. Better to specify, even by calling getDefault(), than to rely on an implicit default.
First we gather a collection of desired date-time values.
int requiredCountOfDays = 10; // The Question demands 10 previous working days.
List<LocalDate> days = new ArrayList<LocalDate>( requiredCountOfDays ); // Collect desired LocalDate objects.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ); // Specify time zone by which to get current date.
LocalDate today = LocalDate.now( timeZone ); // Get the current date at this moment in specified time zone.
LocalDate localDate = today; // Define var to decrement for previous days.
while ( days.size() < requiredCountOfDays ) { // Loop until we fill the list (10 elements).
localDate = localDate.minusDays( 1 ); // Decrement to get previous day.
// Hard-code what days are business days vs weekend days.
boolean isWeekend = ( ( localDate.getDayOfWeek() == DateTimeConstants.SATURDAY ) || ( localDate.getDayOfWeek() == DateTimeConstants.SUNDAY ) ); // Hard-coding for weekend because it is easier to type than coding for the more numerous week days.
if ( !isWeekend ) { // If business day…
days.add( localDate ); // …collect this day.
}
}
Afterwards, we present those values in a localized String format.
List<String> daysOfWeek = new ArrayList<String>( days.size() ); // Collect the same number of LocalDate objects, rendered as Strings.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE" ); // Generate name of day-of-week, abbreviated.
for ( LocalDate day : days ) {
String dayOfWeek = formatter.print( day ); // Generate String representation.
daysOfWeek.add( dayOfWeek ); // Collect the string.
}
Dump to console…
System.out.println( "days: " + days );
System.out.println( "daysOfWeek: " + daysOfWeek );
When run…
days: [2014-06-18, 2014-06-17, 2014-06-16, 2014-06-13, 2014-06-12, 2014-06-11, 2014-06-10, 2014-06-09, 2014-06-06, 2014-06-05]
daysOfWeek: [Wed, Tue, Mon, Fri, Thu, Wed, Tue, Mon, Fri, Thu]