I'm trying to get flights for 8 days starting from Sunday to the next Sunday.
The way I have implemented it now is by displaying the 7 days starting the selected date from my form.
// set up calendar for sunday
Calendar sunday = Calendar.getInstance();
sunday.setTime(form.getDate());
sunday.add(Calendar.DAY_OF_WEEK, -1 * (sunday.get(Calendar.DAY_OF_WEEK) - 1));
//set up calendar for next saturday
Calendar saturday = Calendar.getInstance();
saturday.setTime(sunday.getTime());
saturday.add(Calendar.DAY_OF_WEEK, 7);
Since the max of DAY_OF_WEEK is 7, what do I need to use instead?
I tried changing this line:
saturday.add(Calendar.DAY_OF_WEEK, 7);
to the following one:
saturday.add(Calendar.DATE, 8);
I already tried couple changes but no luck.
Any advice?
Try using Calendar.DAY_OF_YEAR.
import java.text.*;
import java.util.*;
DateFormat dateFormat = new SimpleDateFormat("EEE, MMM dd, yyyy hh:mm:ss a z");
Calendar sunday = new GregorianCalendar();
sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // Set day of week to Sunday.
System.out.println(dateFormat.format(sunday.getTime()));
sunday.add(Calendar.DAY_OF_YEAR, 7); // Add seven days.
System.out.println(dateFormat.format(sunday.getTime()));
Output
Sun, Dec 04, 2016 11:47:32 PM EST
Sun, Dec 11, 2016 11:47:32 PM EST
You can create new calendar objects without modifying the existing one, by making a copy.
import java.text.*;
import java.util.*;
public class CalendarUtils {
public static void main(String[] args) {
Calendar sunday = CalendarUtils.getThisSundaysDate();
Calendar saturday = CalendarUtils.daysFrom(sunday, 6);
CalendarUtils.printDates(sunday, saturday);
}
public static Calendar getThisSundaysDate() {
Calendar sunday = new GregorianCalendar();
sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
return sunday;
}
public static Calendar daysFrom(Calendar cal, int days) {
Calendar newCal = copyCalendar(cal);
newCal.add(Calendar.DAY_OF_YEAR, days);
return newCal;
}
public static Calendar copyCalendar(Calendar cal) {
Calendar copy = new GregorianCalendar();
copy.setTime(cal.getTime());
return copy;
}
public static void printDates(Calendar from, Calendar to) {
DateFormat dateFormat = new SimpleDateFormat("EEE, MMMM dd, yyyy hh:mm:ss a z");
System.out.println(dateFormat.format(from.getTime()));
System.out.println(dateFormat.format(to.getTime()));
}
}
If you're using Java 8, you should use the new java.time classes. In this case, you'd want to use the LocalDate class, and the TemporalAdjusters class, with it's previous(DayOfWeek) method.
Alternatively, use the previousOrSame(DayOfWeek), depending on what should happen if the reference date is a Sunday.
Example, using today as the reference date:
LocalDate refDate = LocalDate.now();
LocalDate prevSunday = refDate.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
LocalDate nextSunday = prevSunday.plusDays(7);
DateTimeFormatter fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
System.out.println("Ref. Date: " + refDate.format(fmt));
System.out.println("Prev. Sunday: " + prevSunday.format(fmt));
System.out.println("Next. Sunday: " + nextSunday.format(fmt));
Output
Ref. Date: Monday, December 5, 2016
Prev. Sunday: Sunday, December 4, 2016
Next. Sunday: Sunday, December 11, 2016
Related
I have a date and I need to know the last week and last month before the date.
For example,
on July 15, 2018, Its last week was from July 2 to July 8. Its last month was June 1 to June 30.
on July 16, 2018, Its last week was from July 9 to July 15. Its last month was June 1 to June 30.
on July 17, 2018, Its last week was from July 9 to July 15. Its last month was June 1 to June 30.
It is different from get-date-of-first-day-of-week-based-on-localdate-now-in-java-8, my problem is to get last week or last month.
You can use these helper methods.
public static LocalDate[] getPreviousWeek(LocalDate date) {
final int dayOfWeek = date.getDayOfWeek().getValue();
final LocalDate from = date.minusDays(dayOfWeek + 6); // (dayOfWeek - 1) + 7
final LocalDate to = date.minusDays(dayOfWeek);
return new LocalDate[]{from, to};
}
public static LocalDate[] getPreviousMonth(LocalDate date) {
final LocalDate from = date.minusDays(date.getDayOfMonth() - 1).minusMonths(1);
final LocalDate to = from.plusMonths(1).minusDays(1);
return new LocalDate[]{from, to};
}
There are in fact many ways to write this. I would suggest you to do some exploration on your own.
You can easly do that with Java 8 LocalDate, here's my solution:
import java.time.LocalDate;
LocalDate now = LocalDate.now();
LocalDate weekStart = now.minusDays(7+now.getDayOfWeek().getValue()-1);
LocalDate weekEnd = now.minusDays(now.getDayOfWeek().getValue());
LocalDate previousMonth = now.minusMonths(1);
LocalDate monthStart = previousMonth.withDayOfMonth(1);
LocalDate monthEnd = previousMonth.withDayOfMonth(previousMonth.getMonth().maxLength());
System.out.println("WeekStart:"+weekStart+", weekEnd:"+weekEnd+", monthStart:"+monthStart+", monthEnd:"+monthEnd);
Result
WeekStart:2018-07-09, weekEnd:2018-07-15, monthStart:2018-06-01, monthEnd:2018-06-30
If you change the now line with
LocalDate now = LocalDate.of(2018,07,15);
You'll get:
WeekStart:2018-07-02, weekEnd:2018-07-08, monthStart:2018-06-01, monthEnd:2018-06-30
ZonedDateTime is useful for that.
import java.time.*;
import java.time.format.DateTimeFormatter;
class DateTest
{
public static void main (String[] args) throws java.lang.Exception
{
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd MMM yyyy");
ZoneId usCentral = ZoneId.of("America/Chicago");
LocalDateTime localDateTime = LocalDateTime.of(2018, Month.JULY, 16, 9, 30);
ZonedDateTime input = ZonedDateTime.of(localDateTime, usCentral);
System.out.println("Input date = " + format.format(input));
ZonedDateTime startDate = input.minusWeeks(1).with(DayOfWeek.MONDAY);
System.out.println("Start date = " + format.format(startDate));
ZonedDateTime endDate = startDate.plusDays(6);
System.out.println("End date = " + format.format(endDate));
}
}
Output:
Input date = 16 Jul 2018
Start date = 09 Jul 2018
End date = 15 Jul 2018
Not sure if you got a Date object, hopefully you got.
From date object you can get Instant with method toInstant()
(To pasrse String to date..
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
date format must be addapted to your needs ofcourse
)
Instant.now().minus(Duration.ofDays(7))); // last week
Instant.now().minus(Duration.of(1,ChronoUnit.MONTHS)) // last month
I need to convert Monthname + Year to a valid date range. It needs to work with leap years etc.
Examples
getDateRange("Feb",2015)
should find the range 2015-02-01 -- 2015-02-28
While
getDateRange("Feb",2016)
should find the range 2016-02-01 -- 2016-02-29
In Java 8, you can do that using TemporalAdjusters,
LocalDate firstDate= date.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDate= date.with(TemporalAdjusters.lastDayOfMonth());
If you have only year and month, it is better to use YearMonth. From YearMonth you can easily get length of that month.
YearMonth ym= YearMonth.of(2015, Month.FEBRUARY);
int monthLen= ym.lengthOfMonth();
Java 8 made Date-Time operations very simple.
For Java 7 and below you could get away with something like this;
void getDate(String month, int year) throws ParseException {
Date start = null, end = null;
//init month and year
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
Date parse = sdf.parse(month);
Calendar instance = Calendar.getInstance();
instance.setTime(parse);
instance.set(Calendar.YEAR, year);
//start is default first day of month
start = instance.getTime();
//calculate end
instance.add(Calendar.MONTH, 1);
instance.add(Calendar.DAY_OF_MONTH, -1);
end = instance.getTime();
System.out.println(start + " " + end);
}
The output would be for "Feb", 2015:
Sun Feb 01 00:00:00 EET 2015
Sat Feb 28 00:00:00 EET 2015
Java 7 solution with default Java tools:
public static void getDateRange(String shortMonth, int year) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
// the parsed date will be the first day of the given month and year
Date startDate = format.parse(shortMonth + " " + year);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
// set calendar to the last day of this given month
calendar.set( Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
// and get a Date object
Date endDate = calendar.getTime();
// do whatever you need to do with your dates, return them in a Pair or print out
System.out.println(startDate);
System.out.println(endDate);
}
Try (untested):
public List<LocalDate> getDateRange(YearMonth yearMonth){
List<LocalDate> dateRange = new ArrayList<>();
IntStream.of(yearMonth.lengthOfMonth()).foreach(day -> dateRange.add(yearMonth.at(day));
return dateRange
}
Java 8 provides new date API as Masud mentioned.
However if you are not working under a Java 8 environment, then lamma date is a good option.
// assuming you know the year and month already. Because every month starts from 1, there should be any problem to create
Date fromDt = new Date(2014, 2, 1);
// build a list containing each date from 2014-02-01 to 2014-02-28
List<Date> dates = Dates.from(fromDt).to(fromDt.lastDayOfMonth()).build();
I am trying to find out the specific date from a given input string, which can be like "201411W3". I know that the week is 3rd from this string(W3) and the event will be on Friday, so I want to find the date of the 3rd Friday. I did something like this:
public static Date getLastFriday( int month, int year ) {
Calendar cal = Calendar.getInstance();
cal.set( year, month, 1 );
cal.add( Calendar.DAY_OF_MONTH, - ( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 8 ) );
return cal.getTime();
}
when I call this method: getLastFriday(11, 2014), I get the value "Fri Nov 21 13:16:57 EST 2014" which I need to parse to find out the date. is there any way to get just the date from the result?
Thanks!
If I understood you, then you can use below code as reference -
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Test{
public static void main (String[] args)
{
String str="201411W3";
String[] strSplitted = str.split("W");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Integer.parseInt(strSplitted[0].substring(4,6))-1);
calendar.set(Calendar.YEAR, Integer.parseInt(strSplitted[0].substring(0,4)));
calendar.set(Calendar.DAY_OF_MONTH, 1);
if(calendar.get(Calendar.DAY_OF_WEEK)==7)
{
calendar.set(Calendar.WEEK_OF_MONTH, Integer.parseInt(strSplitted[1])+1);
}
else
{
calendar.set(Calendar.WEEK_OF_MONTH, Integer.parseInt(strSplitted[1]));
}
calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
System.out.println(formattedDate);
}
}
Output : 2014-11-21 You can change the format to any format you want.
If you just want to get the month and day without the seconds, you could call .get(Calendar.MONTH) and .get(Calendar.DATE) and pass them into the constructor of a new date object and return that object.
More info: here
Use this SimpleDateFormat
I didn't test the following code but it will work like:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date myDate = sdf.parse("Fri Nov 21 13:16:57 EST 2014");
I have a date object myDate(say).
After doing the following:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.DATE, 24);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.HOUR,13);
cal.set(Calendar.MINUTE,45);
cal.set(Calendar.SECOND,52);
I want to set the myDate object to the above values and hence show the below output.
Mon Sep 09 13:45:52 PST 2013
Please let me know how to do it.
import java.util.*;
public class DateTest {
public static void main(String[] args) {
Date myDate;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DATE, 24);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.HOUR,13);
cal.set(Calendar.MINUTE,45);
cal.set(Calendar.SECOND,52);
myDate = cal.getTime();
System.out.println(myDate);
}
}
The months attribute starts from January = zero. Why oh why did Sun do such a counter-intuitive thing, I don't know.
import java.util.*;
public class DateTest {
public static void main(String[] args) {
Date myDate;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DATE, 24);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.HOUR,13);
cal.set(Calendar.MINUTE,45);
cal.set(Calendar.SECOND,52);
myDate = cal.getTime();
System.out.println(myDate);
}
}
One other consideration, the output has a timezone in it - if you want the timezone of the Java installation, no probs. If you want PST and the Java timezone default is somewhere else, then use the following constructor:
TimeZone timezone = TimeZone.getTimeZone("America/Los_Angeles");
Calendar cal = Calendar.getInstance(timezone);
You can write:
myDate.setTime(cal.getTimeInMillis());
Using SimpleDateFormat:
new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").format(cal.getTime())
I would like to take a date object like "Sat Feb 17 20:49:54 +0000 2007" and change the year variable to the current year dynamically to something like this "Sat Feb 17 20:49:54 +0000 2012" what would be the best way to do this in java?
Construct a Calendar from the Date, use the Calendar to set the year, and then get back a Date object from the Calendar.
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.YEAR, 2012);
date = c.getTime();
If that's already a date object, you can do this:
Calendar cal = Calendar.getInstance();
int currentYear = cal.get(Calendar.YEAR);
cal.setTime(dateObj);
//set the year to current year
cal.set(Calendar.YEAR, currentYear);
//new date object with current year
dateObj = cal.getTime();
If that's a string, you can parse the string to a Java Date object first using SimpleDateFormat:
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
And the use the above calendar object.
Based on what you asked for, this is how you do that:
try {
DateFormat dateFormat = new SimpleDateFormat("E, dd MMM HH:mm:ss Z yyyy");
date = (Date) dateFormat.parse("Sat, Feb 17 20:49:54 +0000 2007");
Calendar cal = dateFormat.getCalendar();
cal.set(Calendar.YEAR, 2012);
} catch (ParseException pe) {
//ParseException Handling
} catch(Exception e) {
//Exception Handling
}
Another option would be to utilize JodaTime API
import org.joda.time.DateTime;
import org.joda.time.MutableDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class App
{
public static void main( String[] args )
{
//Sat Feb 17 20:49:54 +0000 2007
DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE MMM dd H:m:s Z yyyy");
DateTime dt = fmt.parseDateTime("Sat Feb 17 20:49:54 +0000 2007");
MutableDateTime mdt = dt.toMutableDateTime();
mdt.setYear(new DateTime().getYear());
System.out.println(fmt.print(mdt));
}
}