In Joda-Time, is there a way to get the date of the first day of the week(monday).
for instance i want to find out what date was this weeks monday based on todays current date 21/01/11
Cheers in advance.
edit: i also wish to find the date for the end of the week i.e sunday's date. cheers
Try LocalDate.withDayOfWeek:
LocalDate now = new LocalDate();
System.out.println(now.withDayOfWeek(DateTimeConstants.MONDAY)); //prints 2011-01-17
System.out.println(now.withDayOfWeek(DateTimeConstants.SUNDAY)); //prints 2011-01-23
LocalDate today = new LocalDate();
LocalDate weekStart = today.dayOfWeek().withMinimumValue();
LocalDate weekEnd = today.dayOfWeek().withMaximumValue();
Will give you the first and last days i.e Monday and sunday
Another option is to use roundFloorCopy. This looks like the following:
LocalDate startOfWeek = new LocalDate().weekOfWeekyear().roundFloorCopy();
For the last day of the standard week (Sunday) use roundCeilingCopy and minusDays…
LocalDate lastDateOfWeek = new LocalDate().weekOfWeekyear().roundCeilingCopy().minusDays( 1 );
Also works for DateTime. And works for end of week (exclusive).
DateTime dateTime = new DateTime();
DateTime startOfWeek = dateTime.weekOfWeekyear().roundFloorCopy();
DateTime endOfWeek = dateTime.weekOfWeekyear().roundCeilingCopy();
Dump to console…
System.out.println( "dateTime " + dateTime );
System.out.println( "startOfWeek " + startOfWeek );
System.out.println( "endOfWeek " + endOfWeek );
When run…
dateTime 2014-01-24T00:00:34.955-08:00
startOfWeek 2014-01-20T00:00:00.000-08:00
endOfWeek 2014-01-27T00:00:00.000-08:00
You can use the getDayOfWeek() method that gives you back 1 for Monday, 2 for Tue, .., 7 for Sunday in order to go back that many days and reach Monday:
import org.joda.time.DateTime;
public class JodaTest {
public static void main(String[] args) {
DateTime date = new DateTime();
System.out.println(date);
//2011-01-21T15:06:18.713Z
System.out.println(date.minusDays(date.getDayOfWeek()-1));
//2011-01-17T15:06:18.713Z
}
}
See the section "Querying DateTimes" of the Joda-Time user guide.
Here is the general algorithm I would follow:
find the day-of-week of the target date (Jan 21 2011 as you mentioned)
determine how many days ahead of Monday this is
Subtract the value of #2 from the target date using dateTime.minusDays(n)
Related
I want to select Sunday before first Monday of the passed month.
That Sunday may be in the same month or the previous month but I want date of Sunday. I tried below logic for getting Sunday, it works for the current month but if I try passing some another month like Nov-2017 then again I have to change MONDAY-2 to MONDAY-3. So this is not the correct way. So how can I achieve this ?
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
c.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY - 2);
System.out.println("Date " + c.getTime());
I want to pass date to the code. So how can i do it ? like if I have date saved in variable then according to the input provided by that variable it should calculate the logic and provide the output
#Test
public void testDate() throws ParseException {
SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
Date d = fmt.parse("01-Nov-2017");
System.out.println(d);
Calendar c = Calendar.getInstance();
c.setTime(d);
getSundayBefore1thMondayOfMonth(c);
}
public void getSundayBefore1thMondayOfMonth(Calendar c) {
c.set(Calendar.DAY_OF_MONTH, 1);
int wd = c.get(Calendar.DAY_OF_WEEK);
if (wd > Calendar.MONDAY ) {
c.add(Calendar.DAY_OF_MONTH, 7);
}
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(c.getTime());
c.add(Calendar.DAY_OF_MONTH, -1);
System.out.println(c.getTime());
}
Wed Nov 01 00:00:00 CST 2017
Mon Nov 06 00:00:00 CST 2017
Sun Nov 05 00:00:00 CST 2017
If you are using Java 8, Then you can use java.time library and you can just use :
LocalDate firstMondayOfMonth = LocalDate.now().with(
TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)
);// This return 2018-01-01
LocalDate sunday = firstMondayOfMonth.minusDays(1);//This return 2017-12-31
To test with November 2017 you can use LocalDate.of instead LocalDate.now() like this :
LocalDate firstMondayOfMonth = LocalDate.of(2017, Month.NOVEMBER, 1).with(
TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)
);// This return 2017-11-06
LocalDate firstSunday = firstMondayOfMonth.minusDays(1);// This return 2017-11-05
tl;dr
YearMonth
.now() // Current year-month. Tip: Better to pass the optional time zone, as shown further down in this Answer.
.atDay( 1 ) // First of the current month.
.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) ) // Move from first day of month to the following Monday, or stay on the first if it already a Monday.
.minusDays( 1 ) // Move back one day from Monday to get a Sunday. May be in current month or in previous month.
java.time
You are using troublesome old date-date classes that are now legacy, supplanted by the java.time classes.
Determining the current month means determining the current date. Determining the current date requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
The YearMonth class represent the entire month.
YearMonth currentYearMonth = YearMonth.now( z ) ;
From that we can get the first of the month.
LocalDate firstOfMonth = currentYearMonth.atDay( 1 ) ;
We can move to a certain day of the week by calling on a TemporalAdjuster.
LocalDate firstMondayOfMonth = firstOfMonth.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) ) ;
LocalDate sundayBeforeFirstMondayOfMonth = firstMondayOfMonth.with( TemporalAdjusters.previous( DayOfWeek.SUNDAY ) ) ;
Logically, that last line could be replaced with .minusDays( 1 ) as we know the previous Sunday immediately precedes our Monday by definition.
In the code below, first we get the first monday in the month. Then we just subtract 1 day.
// input
int year = 2017;
int month = Calendar.NOVEMBER;
// get first monday of the month
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
c.set(Calendar.MONTH, month);
c.set(Calendar.YEAR, year);
System.out.println("Date " + c.getTime());
// subtract 1
c.add(Calendar.DAY_OF_MONTH, -1);
System.out.println("Date " + c.getTime());
Try this:
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
calendar.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
calendar.add(Calendar.DATE, -1);
System.out.println(calendar.getTime());
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek( Calendar.MONDAY); //Monday is first day of a week
c.setMinimalDaysInFirstWeek( 1); //first week of month is the week that has at least one day in this month
//c.setMinimalDaysInFirstWeek( 7); //first week of month must be a full week
c.set(Calendar.WEEK_OF_MONTH, 1); //move to first week of month
System.out.println("Date " + c.getTime());
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); //move to Monday
System.out.println("Date " + c.getTime());
c.add( Calendar.DAY_OF_MONTH, -1); //go back one day
System.out.println("Date " + c.getTime());
Choose one of the c.setMinimalDaysInFirstWeek() method depending on what the first week of month means to you.
In Java 8, you can use the below code:
public static void getSundayBeforeFirstMondayOfMonth(LocalDate date){
date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)).minusDays(1);
}
And, call the above method like below as per the requirement:
public static void callerMethod(){
// Call with Current Date
getSundayBeforeFirstMondayOfMonth(LocalDate.now());
//Call with Custom Date
LocalDate customDate = LocalDate.parse("27-11-2017", DateTimeFormatter.ofPattern("DD-MM-YYYY"));
getSundayBeforeFirstMondayOfMonth(customDate);
}
I have verified that the date is read correctly from a file, but once I use SimpleDateFormat.format with the pattern "dd/MM/yy" it suddenly adds a month. This leads me to believe lenient mode is calculating the wrong value. But I have no idea what would make it add a full month.
Some example dates I read:
16/09/2013
23/09/2013
30/09/2013
07/10/2013
14/10/2013
21/10/2013
The code used to parse the date (it's a wrapper around Calendar I made):
public static SimpleDateTime parseDate(String date)
{
String[] dateParts = date.split("[-\\.:/]");
int day = Integer.parseInt(dateParts[0]);
int month = Integer.parseInt(dateParts[1]);
int year = Integer.parseInt(dateParts[2]);
return new SimpleDateTime(dag, maand, jaar);
}
The constructor used here:
public SimpleDateTime(int day, int month, int year)
{
date = Calendar.getInstance();
date.setLenient(true);
setDay(day);
setMonth(month);
setYear(year);
}
The setters for day, month and year:
public void setYear(int year)
{
date.set(Calendar.YEAR, year);
}
public void setMonth(int month)
{
date.set(Calendar.MONTH, month);
}
public void setDay(int day)
{
date.set(Calendar.DAY_OF_MONTH, day);
}
And the code used to format the date:
public String toString(String pattern)
{
String output = new SimpleDateFormat(pattern, Locale.getDefault()).format(date.getTime());
return output;
}
where the pattern passed is:
"dd/MM/yy"
Intended to print a date as:
16/09/13
23/09/13
Instead I get:
16/10/13
23/10/13
January is 0 in Java; February is 1 and so on.
See Calendar.JANUARY, Calendar.FEBRUARY.
So when you're reading 1 from the file
you think you read JAN but you read FEB.
You should do: date.set(Calendar.MONTH, month-1); to fix this.
Months are indexed from 0 not 1 so 10 is November and 11 will be December.
Calendar.MONTH
From documentation:
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year is JANUARY; the last depends on the number of months in a year.
So if you check JANUARY you see it starts in zero.
Make sure your month is in the interval 0-11. Possibly it is in 1-12.
The reason for this is that the counting starts at 0.
January == 0
February == 1
and so on. See the documentation.
THe problem is that you pass 9 to SimpleDateFormat and since month are indexed from 0 to 11 it will parse month '9' as the 10th month.
You need to subtract 1 from the month :)
Calendar class in Java holds months starting from 0, hence when you set the month as 0, it would consider it as January. SimpleDateFormat provides for a way to correctly display the value as 01.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 0);
System.out.println(new SimpleDateFormat("dd/MM/yy").format(cal.getTime()));
Output:
29/01/14
The workaround for you to align you file that Calendar can work with (since December - or 12 would trickle over to the next year) or modify your logic to pick Constants like:
cal.set(Calendar.MONTH, Calendar.JANUARY);
The answer by peter.petrov is almost correct, except for one major problem. Like your question, it neglects to account for time zone.
For your information, this kind of work is much easier in Joda-Time (or new java.time.* classes in Java 8). Joda-Time is so much cleaner you won't even feel the need to create a wrapper class.
// Specify the time zone for which the incoming date is intended.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Brussels" );
String input = "16/09/2013";
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy").withZone( timeZone );
DateTime dateTime = formatter.parseDateTime( input );
String output = formatter.print( dateTime );
Dump to console…
System.out.println( "dateTime: " + dateTime );
System.out.println( "output: " + output );
System.out.println( "millis since Unix epoch: " + dateTime.getMillis() );
When run…
dateTime: 2013-09-16T00:00:00.000+02:00
output: 16/09/2013
millis since Unix epoch: 1379282400000
If possible I would prefer a joda or non-joda solution for the scenario below
Lets say if my week starts on 02/05/2012 and the given current date is 02/22/2011. I need to calculate the week start and end date for the given current date. So my solution should have the week start as 02/19 and week ends at 02/25.
For simplicity, I have set my week start here as 02/05/2011 but it could be any day potentially and my week always has 7 days.
My existing code is below but doesnt seem to work as expected.
public Interval getWeekInterval(Date calendarStartDate, Date date)
{
Calendar sDate = Calendar.getInstance();
sDate.setTime(getMidnightDate(calendarStartDate));
Calendar eDate = Calendar.getInstance();
eDate.setTime(date);
Calendar weekStartDate = (Calendar) sDate.clone();
logger.debug("Date:" + sDate.getTime());
while (sDate.before(eDate)) {
weekStartDate = sDate;
sDate.add(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
}
return new Interval(weekStartDate.getTime(), sDate.getTime());
}
Defining A Week
If you are using date-time objects, you should define a week as up to but not including the first moment of the day after the end of week. As seen in this diagram.
This approach is known as Half-Open. This approach is commonly used for working with spans of time.
The reason is because, logically, that last moment of the day before the new day is infinitely divisible as a fraction of a second. You may think that using ".999" would handle that for milliseconds, but then you'd mistaken when writing for the new java.time.* classes in Java 8 that have nanosecond resolution rather than millisecond. You may think think that using ".999999999" would handle that case, but then you’d be mistaken when handling date-time values from many databases such as Postgres that use microsecond resolution, ".999999".
In the third-party open-source Joda-Time library, this Half-Open logic is how its Interval class works. The beginning is inclusive and the ending is exclusive. This works out nicely. Similarly, calling plusWeeks(1) on a DateTime to add a week to the first moment of a day gives you the first moment of the 8th day later (see example below).
Time Zone
The question and other answers ignores the issue of time zone. If you do not specify, you'll be getting the default time zone. Usually better to specify a time zone, using a proper time zone name (not 3-letter code).
Joda-Time
Avoid the java.util.Date & Calendar classes bundled with Java. They are notoriously troublesome.
Here is some example code using Joda-Time 2.3.
CAVEAT: I have not tested of of the below code thoroughly. Just my first take, a rough draft. May well be flawed.
Standard Week (Monday-Sunday)
The Joda-Time library is built around the ISO 8601 standard. That standard defines the first day of the week as Monday, last day as Sunday.
If that meets your definition of a week, then getting the beginning and ending is easy.
UPDATE As an alternative to the discussion below, see this very clever and very simple one-liner solution by SpaceTrucker.
Simply forcing the day-of-week works because Joda-Time assumes you want:
Monday to be before (or same as) today.
Sunday to be after (or same as) today.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = new DateTime( timeZone );
DateTime weekStart = now.withDayOfWeek( DateTimeConstants.MONDAY ).withTimeAtStartOfDay();
DateTime weekEnd = now.withDayOfWeek(DateTimeConstants.SUNDAY).plusDays( 1 ).withTimeAtStartOfDay();
Interval week = new Interval( weekStart, weekEnd );
Dump to console…
System.out.println( "now: " + now );
System.out.println( "weekStart: " + weekStart );
System.out.println( "weekEnd: " + weekEnd );
System.out.println( "week: " + week );
When run…
now: 2014-01-24T06:29:23.043+01:00
weekStart: 2014-01-20T00:00:00.000+01:00
weekEnd: 2014-01-27T00:00:00.000+01:00
week: 2014-01-20T00:00:00.000+01:00/2014-01-27T00:00:00.000+01:00
To see if a date-time lands inside that interval, call the contains method.
boolean weekContainsDate = week.contains( now );
Non-Standard Week
If that does not meet your definition of a week, you a twist on that code.
DateTimeZone timeZone = DateTimeZone.forID( "America/New_York" );
DateTime now = new DateTime( timeZone );
DateTime weekStart = now.withDayOfWeek( DateTimeConstants.SUNDAY ).withTimeAtStartOfDay();
if ( now.isBefore( weekStart )) {
// If we got next Sunday, go back one week to last Sunday.
weekStart = weekStart.minusWeeks( 1 );
}
DateTime weekEnd = weekStart.plusWeeks( 1 );
Interval week = new Interval( weekStart, weekEnd );
Dump to console…
System.out.println( "now: " + now );
System.out.println( "weekStart: " + weekStart );
System.out.println( "weekEnd: " + weekEnd );
System.out.println( "week: " + week );
When run…
now: 2014-01-24T00:54:27.092-05:00
weekStart: 2014-01-19T00:00:00.000-05:00
weekEnd: 2014-01-26T00:00:00.000-05:00
week: 2014-01-19T00:00:00.000-05:00/2014-01-26T00:00:00.000-05:00
First day of week depends on the country.
What makes the calculation fragile, is that one may break the year boundary, and the week number (Calendar.WEEK_OF_YEAR). The following would do:
Calendar currentDate = Calendar.getInstance(Locale.US);
int firstDayOfWeek = currentDate.getFirstDayOfWeek();
Calendar startDate = Calendar.getInstance(Locale.US);
startDate.setTime(currentDate.getTime());
//while (startDate.get(Calendar.DAY_OF_WEEK) != firstDayOfWeek) {
// startDate.add(Calendar.DATE, -1);
//}
int days = (startDate.get(Calendar.DAY_OF_WEEK) + 7 - firstDayOfWeek) % 7;
startDate.add(Calendar.DATE, -days);
Calendar endDate = Calendar.getInstance(Locale.US);
endDate.setTime(startDate.getTime());
endDate.add(Calendar.DATE, 6);
One bug in Calendar breaks your code, clone, seems to simply give the identical object, hence at the end you have identical dates. (Java 7 at least).
DateTime sDateTime = new DateTime(startDate); // My calendar start date
DateTime eDateTime = new DateTime(date); // the date for the week to be determined
Interval interval = new Interval(sDateTime, sDateTime.plusWeeks(1));
while(!interval.contains(eDateTime))
{
interval = new Interval(interval.getEnd(), interval.getEnd().plusWeeks(1));
}
return interval;
Try this (pseudo-code):
// How many days gone after reference date (a known week-start date)
daysGone = today - referenceDate;
// A new week starts after each 7 days
dayOfWeek = daysGone % 7;
// Now, we know today is which day of the week.
// We can find start & end days of this week with ease
weekStart = today - dayOfWeek;
weekEnd = weekStart + 6;
Now, we can shorten all of this to two lines:
weekStart = today - ((today - referenceDate) % 7);
weekEnd = weekStart + 6;
Note that we subtracted date values like integers to show algorithm. You have to write your java code properly.
How would I go about getting the first day of the month? So for January, of this year, it would return Sunday. And then for February it would return Wednesday.
To get the first date of the current month, use java.util.Calendar. First get an instance of it and set the field Calendar.DAY_OF_MONTH to the first date of the month. Since the first day of any month is 1, inplace of cal.getActualMinimum(Calendar.DAY_OF_MONTH), 1 can be used here.
private Date getFirstDateOfCurrentMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
return cal.getTime();
}
You can create a Calendar with whatever date you want and then do set(Calendar.DAY_OF_MONTH, 1) to get the first day of a month.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, 25);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.YEAR, 2012);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDayOfMonth = cal.getTime();
DateFormat sdf = new SimpleDateFormat("EEEEEEEE");
System.out.println("First Day of Month: " + sdf.format(firstDayOfMonth));
public int getFirstDay(){
Calendar c=new GregorianCalendar();
c.set(Calendar.DAY_OF_MONTH, 1);
return c.get(Calendar.DAY_OF_WEEK);
}
From there you can see if the int is equal to Calendar.SUNDAY, Calendar.MONDAY, etc.
In the Java 8 you can use the TemporalAdjusters:
This is an example:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
/**
* Dates in Java8
*
*/
public class App {
public static void main(String[] args) {
LocalDate localDate = LocalDate.now();
System.out.println("Day of Month: " + localDate.getDayOfMonth());
System.out.println("Month: " + localDate.getMonth());
System.out.println("Year: " + localDate.getYear());
System.out.printf("first day of Month: %s%n",
localDate.with(TemporalAdjusters.firstDayOfMonth()));
System.out.printf("first Monday of Month: %s%n", localDate
.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)));
System.out.printf("last day of Month: %s%n",
localDate.with(TemporalAdjusters.lastDayOfMonth()));
System.out.printf("first day of next Month: %s%n",
localDate.with(TemporalAdjusters.firstDayOfNextMonth()));
System.out.printf("first day of next Year: %s%n",
localDate.with(TemporalAdjusters.firstDayOfNextYear()));
System.out.printf("first day of Year: %s%n",
localDate.with(TemporalAdjusters.firstDayOfYear()));
LocalDate tomorrow = localDate.plusDays(1);
System.out.println("Day of Month: " + tomorrow.getDayOfMonth());
System.out.println("Month: " + tomorrow.getMonth());
System.out.println("Year: " + tomorrow.getYear());
}
}
The results would be:
Day of Month: 16
Month: MAY
Year: 2014
first day of Month: 2014-05-01
first Monday of Month: 2014-05-05
last day of Month: 2014-05-31
first day of next Month: 2014-06-01
first day of next Year: 2015-01-01
first day of Year: 2014-01-01
Last in Month Tuesday: 2014-05-27
Day of Month: 17
Month: MAY
Year: 2014
TemporalAdjuster
In java 8 you can use the new LocalDate and LocalTime API.
To achieve the coveted result, give a try to the following. It prints the name of the given day.
import java.time.*;
import java.time.temporal.*;
public class Main {
public static void main(String[] args) {
LocalDate l = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
System.out.println(l.getDayOfWeek());
}
}
Explanation:
now gives you the current date.
by calling with you can pass a TemporalAdjuster which are a key tool for modifying temporal objects.
getDayOfWeek Gets the day-of-week field, which is an enum DayOfWeek.
This includes textual names of the values.
TemporalAdjuster has a brother class, called TemporalAdjusters which contains static methods regarding the adjustments, like the one you are looking for, the firstDayOfMonth
Create java.util.Date or java.util.Calendar object, set date value and use java.text.SimpleDateFormat class method to format it.
Calendar cal=Calendar.getInstance();
cal.set(Calendar.DATE,1);
cal.set(Calendar.MONTH,0);
cal.set(Calendar.YEAR,2012);
SimpleDateFormat sdf=new SimpleDateFormat("EEEE");
System.out.println(sdf.format(cal.getTime()));
java.time
Since Java 8 we can also use YearMonth class which allows us to create LocalDate objects with specified days (first, last). Then We can simply convert these dates to DayOfWeek Enum (Tutorial) and read its name property.
YearMonth ym = YearMonth.of(2012, 1);
String firstDay = ym.atDay(1).getDayOfWeek().name();
String lastDay = ym.atEndOfMonth().getDayOfWeek().name();
System.out.println(firstDay);
System.out.println(lastDay);
result:
SUNDAY
TUESDAY
java.time, soft-coded
The Answer by Pshemo was good and clever, but is hard-coded to English. Let's take a stab at it allowing for localization.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Time zone is crucial to determining a date.
YearMonth yearMonth = YearMonth.now( zoneId );
LocalDate firstOfMonth = yearMonth.atDay( 1 );
Formatter
Generate a textual representation of that LocalDate. We specify a desired Locale, in this case CANADA_FRENCH. If omitted, your JVM’s current default Locale is implicitly applied; better to specify explicit Locale.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "EEEE" ).withZone( zoneId ).withLocale( Locale.CANADA_FRENCH ); // Exactly four 'E' letters means full form. http://docs.oracle.com/javase/8/docs/api/java/time/format/TextStyle.html#FULL
String output = formatter.format( firstOfMonth );
Dump to console.
System.out.println( "output: " + output );
When run.
samedi
DayOfWeek Enum
Another route is to use the DayOfWeek enum. This enum includes a getDisplayName method where you specify both the text style (full name versus abbreviation) and a Locale.
DayOfWeek dayOfWeek = firstOfMonth.getDayOfWeek() ;
String output = dayOfWeek.getDisplayName( TextStyle.FULL_STANDALONE , Locale.CANADA_FRENCH ) ;
Simple and tricky answer
val calendar = Date()
val sdf = SimpleDateFormat("yyyy-MM-01 00:00:00", Locale.getDefault())
var result = sdf.format(calendar)
yyyy-MM-01 -> dd change to 01
This question already has answers here:
Is there a good way to get the date of the coming Wednesday?
(6 answers)
Closed 3 years ago.
I asked How to detect if a date is within this or next week in Java? but the answers were confusing, so now I think if I can find the past Sunday and the coming Sunday, any day in between is this week, and any day between the coming Sunday and the Sunday after that is next week, am I correct ?
So my new question is : How to get the past Sunday and the coming Sunday in Java ?
java.time
Briefly:
LocalDate.now().with( next( SUNDAY ) )
See this code run live at IdeOne.com.
Details
I thought I'd add a Java 8 solution for posterity. Using LocalDate, DayOfWeek, and TemporalAdjuster implementation found in the TemporalAdjusters class.
final LocalDate today = LocalDate.of(2015, 11, 20);
final LocalDate nextSunday = today.with(next(SUNDAY));
final LocalDate thisPastSunday = today.with(previous(SUNDAY));
This approach also works for other temporal classes like ZonedDateTime.
import
As written, it assumes the following static imports:
import java.time.LocalDate;
import static java.time.DayOfWeek.SUNDAY;
import static java.time.temporal.TemporalAdjusters.next;
import static java.time.temporal.TemporalAdjusters.previous;
How about this :
Calendar c=Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
c.set(Calendar.HOUR_OF_DAY,0);
c.set(Calendar.MINUTE,0);
c.set(Calendar.SECOND,0);
DateFormat df=new SimpleDateFormat("EEE yyyy/MM/dd HH:mm:ss");
System.out.println(df.format(c.getTime())); // This past Sunday [ May include today ]
c.add(Calendar.DATE,7);
System.out.println(df.format(c.getTime())); // Next Sunday
c.add(Calendar.DATE,7);
System.out.println(df.format(c.getTime())); // Sunday after next
The result :
Sun 2010/12/26 00:00:00
Sun 2011/01/02 00:00:00
Sun 2011/01/09 00:00:00
Any day between the first two is this week, anything between the last two is next week.
Without using a better time/date package...
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
Calendar now = new GregorianCalendar();
Calendar start = new GregorianCalendar(now.get(Calendar.YEAR),
now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH) );
while (start.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
start.add(Calendar.DAY_OF_WEEK, -1);
}
Calendar end = (Calendar) start.clone();
end.add(Calendar.DAY_OF_MONTH, 7);
System.out.println(df.format(now.getTime()) );
System.out.println(df.format(start.getTime()) );
System.out.println(df.format(end.getTime()) );
If today is Sunday, it is considered the start of the time period. If you want a period of this week and next week (as it sounds from your question), you can substitute 14 instead of 7 in the end.add(...) line. The times are set to midnight for comparison of another object falling between start and end.
First, don't use the Date/Time package from Java. There is a much better utility package called Joda-Time - download that and use it.
To determine if your time is in this week, last week, or any week at all, do this:
Create two Interval objects - one for last week and one for this week
Use the contains( long ) method to determine which interval holds the date you are looking for.
There are several cool ways you can create two back to back weeks. You could set up a Duration of one week, find the start time for the first week, and just create two Intervals based on that start time. Feel free to find any other way that works for you - the package has numerous ways to get to what you want.
EDIT:
Joda-Time can be downloaded here, and here is an example of how Joda would do this:
// Get the date today, and then select midnight of the first day of the week
// Joda uses ISO weeks, so all weeks start on Monday.
// If you want to change the time zone, pass a DateTimeZone to the method toDateTimeAtStartOfDay()
DateTime midnightToday = new LocalDate().toDateTimeAtStartOfDay();
DateTime midnightMonday = midnightToday.withDayOfWeek( DateTimeConstants.MONDAY );
// If your week starts on Sunday, you need to subtract one. Adjust accordingly.
DateTime midnightSunday = midnightMonday.plusDays( -1 );
DateTime midnightNextSunday = midnightSunday.plusDays( 7 );
DateTime midnightSundayAfter = midnightNextSunday.plusDays( 7 );
Interval thisWeek = new Interval( midnightSunday, midnightNextSunday );
Interval nextWeek = new Interval( midnightNextSunday, midnightSundayAfter );
if ( thisWeek.contains( someDate.getTime() )) System.out.println("This week");
if ( nextWeek.contains( someDate.getTime() )) System.out.println("Next week");
Given bellow next Sunday code and you can easily figure out how to find past Sunday.
private static void nextSunday() throws ParseException
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
int days = Calendar.SUNDAY - weekday;
if (days < 0)
{
days += 7;
}
calendar.add(Calendar.DAY_OF_YEAR, days);
System.out.println(sdf.format(calendar.getTime()));
}
I recently developed Lamma Date which is designed to solve this use case:
Date today = new Date(2014, 7, 1); // assume today is 2014-07-01
Date previousSunday = today.previousOrSame(DayOfWeek.SUNDAY); // 2014-06-29
Date nextSunday = today.next(DayOfWeek.SUNDAY); // 2014-07-06
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Date.html
I recommend Calendar.get(Calendar.DAY_OF_WEEK)
You could try to work with the Calendar.WEEK_OF_YEAR field, which gives you the numeric representation of the week within the current year.
#Test
public void testThisAndNextWeek() throws Exception {
GregorianCalendar lastWeekCal = new GregorianCalendar(2010,
Calendar.DECEMBER, 26);
int lastWeek = lastWeekCal.get(Calendar.WEEK_OF_YEAR);
GregorianCalendar nextWeekCal = new GregorianCalendar(2011,
Calendar.JANUARY, 4);
int nextWeek = nextWeekCal.get(Calendar.WEEK_OF_YEAR);
GregorianCalendar todayCal = new GregorianCalendar(2010,
Calendar.DECEMBER, 27);
int currentWeek = todayCal.get(Calendar.WEEK_OF_YEAR);
assertTrue(lastWeekCal.before(todayCal));
assertTrue(nextWeekCal.after(todayCal));
assertEquals(51, lastWeek);
assertEquals(52, currentWeek);
// New Year.. so it's 1
assertEquals(1, nextWeek);
}
My Solution:
LocalDate date = ...;
LocalDate newWeekDate = date.plusDays(1);
while (newWeekDate.getDayOfWeek() != DayOfWeek.SATURDAY &&
newWeekDate.getDayOfWeek() != DayOfWeek.SUNDAY) {
newWeekDate = date.plusDays(1);
}