I am developing an app that constantly monitors the user's physical activity and inactivity levels. I am trying to figure out out to get the starting and ending day of a week when a date is provided. For example, 3 Mar is the date that I am providing and I want to get the starting and ending day of this week -> 27 Feb - 5 Mar. Is it possible to do that?
I am trying to achieve the following design
The following code that I currently have just concatenates the last and first date of the list of activities (one for every day is created).
private String formatDate(List<Activity> activities) {
Calendar calendar = Calendar.getInstance(Locale.UK);
Date date = activities.get(activities.size() - 1).getDate();
calendar.setTime(date);
String output = "" + calendar.get(Calendar.DAY_OF_MONTH) + " "
+ calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.UK);
calendar.setTime(activities.get(0).getDate());
output += " - " + calendar.get(Calendar.DAY_OF_MONTH) + " "
+ calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.UK);
return output;
}
Note: I have to mention that the List as a parameter are all of the activities grouped per week already
However, with this approach it becomes problematic when the person is not using the app (i.e. not logged in -> the app stops monitoring) and the text label could look something like that
(e.g. only one activity for this week)
Any advice please?
It is as simple as doing:
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
What is considered the first day of the week depends on the Locale used.
To get the last day of the week then do:
calendar.add(Calendar.DAY_OF_YEAR, 6);
java.time
The legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat etc.) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Solution using java.time, the modern API:
For ISO 8601 week (Monday to Sunday), you can use ChronoField.DAY_OF_WEEK as 1 for the first day of the week and as 7 for the last day of the week.
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoField;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2017, Month.MARCH, 3);
LocalDate firstDayOfTheWeek = date.with(ChronoField.DAY_OF_WEEK, 1);
System.out.println(firstDayOfTheWeek); // 2017-02-27
LocalDate lastDayOfTheWeek = date.with(ChronoField.DAY_OF_WEEK, 7);
System.out.println(lastDayOfTheWeek); // 2017-03-05
}
}
Alternatively,
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.WeekFields;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2017, Month.MARCH, 3);
LocalDate firstDayOfTheWeek = date.with(WeekFields.ISO.getFirstDayOfWeek());
System.out.println(firstDayOfTheWeek); // 2017-02-27
LocalDate lastDayOfTheWeek = firstDayOfTheWeek.plusDays(6);
System.out.println(lastDayOfTheWeek); // 2017-03-05
}
}
Use WeekFields#of(Locale locale) to get the Locale-specific result (thanks, Ole V.V. for the suggestion):
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2017, Month.MARCH, 3);
System.out.println("France:");
LocalDate firstDayOfTheWeek = date.with(WeekFields.of(Locale.FRANCE).getFirstDayOfWeek());
System.out.println(firstDayOfTheWeek);
LocalDate lastDayOfTheWeek = firstDayOfTheWeek.plusDays(6);
System.out.println(lastDayOfTheWeek);
System.out.println();
System.out.println("USA:");
firstDayOfTheWeek = date.with(WeekFields.of(Locale.US).getFirstDayOfWeek());
System.out.println(firstDayOfTheWeek);
lastDayOfTheWeek = firstDayOfTheWeek.plusDays(6);
System.out.println(lastDayOfTheWeek);
}
}
Output:
France:
2017-02-27
2017-03-05
USA:
2017-03-05
2017-03-11
The documentation of WeekFields.ISO.getFirstDayOfWeek() says:
Gets the first day-of-week.
The first day-of-week varies by culture. For example, the US uses
Sunday, while France and the ISO-8601 standard use Monday. This method
returns the first day using the standard DayOfWeek enum.
Learn more about java.time, the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
You just need to use the Calendar.DAY_OF_WEEK parameter to work out how many days to subtract - for example to print the start and end of the current week:
public static void main(String[] args) {
Calendar calendar = GregorianCalendar.getInstance();
// Subtract number of days to start of week
calendar.add(Calendar.DATE, -(calendar.get(Calendar.DAY_OF_WEEK)-1));
String output = "" + calendar.get(Calendar.DAY_OF_MONTH) + " "
+ calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.UK);
calendar.add(Calendar.DATE, 6);
output += " - " + calendar.get(Calendar.DAY_OF_MONTH) + " "
+ calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.UK);
System.out.println(output);
}
Thanks to #BarrySW19 and #john16384, here is the working method:
private String formatDate(List<Activity> activities) {
Calendar calendar = Calendar.getInstance(Locale.UK);
Date date = activities.get(activities.size() - 1).getDate();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
String output = "" + calendar.get(Calendar.DAY_OF_MONTH) + " "
+ calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.UK);
calendar.add(Calendar.DAY_OF_YEAR, 6);
output += " - " + calendar.get(Calendar.DAY_OF_MONTH) + " "
+ calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.UK);
return output;
}
Related
I want to return the value of the calendar + 14 months using the SimpleDateFormat but am getting the below error.
private fun bestBeforeDate(cal: Calendar = Calendar.getInstance()): String
{
cal.add(Calendar.MONTH, 14)
val format1 = SimpleDateFormat("dd-MM-yyy", Locale.getDefault()).format(this)
return getString(R.string.best_before_date) + format1.format(cal)
}
java.lang.IllegalArgumentException: Cannot format given Object as a Date
java.time and ThreeTenABP
Sorry, I can write this in Java only. Please translate yourself. Your task is best solved using java.time, the modern Java date and time API.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
LocalDate date = LocalDate.now(ZoneId.of("Europe/London")).plusMonths(14);
String result = date.format(dateFormatter);
System.out.println("Result: " + result);
Output when running today:
Result: 22-12-2020
Fixing your code
If you insist on using the notoriously troublesome and long outdated SimpleDateFormat class, just remove .format(this) from your code. I bet the exception is coming from there, and it’s wrong since you have an almost correct call to the format method in the following line.
private fun bestBeforeDate(cal: Calendar = Calendar.getInstance()): String
{
cal.add(Calendar.MONTH, 14)
val format1 = SimpleDateFormat("dd-MM-yyyy")
return getString(R.string.best_before_date) + format1.format(cal.time)
}
The format method expects either a Date (another poorly designed and long outdated class) or a Long. Since this was neither of those, you got the exception.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
import java.util.Calendar;
import java.util.TimeZone;
/**
* Java program to add, subtract dates, month and year using Calendar in Java.
* Apart from date, Calendar class also provide time related information and can
* be used to add and subtract hours, minutes and seconds from time in Java.
*
* #author Shahzad Ali
*/
public class DateAndTimeArithmetic {
public static void main(String args[]){
//Java calendar in default timezone and default locale
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("current date: " + getDate(cal));
//adding days into Date in Java
cal.add(Calendar.DATE, 2);
System.out.println("date after 2 days : " + getDate(cal));
//subtracting days from Date in Java
cal.add(Calendar.DATE, -2);
System.out.println("date before 2 days : " + getDate(cal));
//adding moths into Date
cal.add(Calendar.MONTH, 5);
System.out.println("date after 5 months : " + getDate(cal));
//subtracting months from Date
cal.add(Calendar.MONTH, -5);
System.out.println("date before 5 months : " + getDate(cal));
//adding year into Date
cal.add(Calendar.YEAR, 5);
System.out.println("date after 5 years : " + getDate(cal));
//subtracting year from Date
cal.add(Calendar.YEAR, -5);
System.out.println("date before 5 years : " + getDate(cal));
//date after 200 days from now, takes care of how many days are in month
//for years calendar takes care of leap year as well
cal.add(Calendar.DATE, 200);
System.out.println("date after 200 days from today : " + getDate(cal));
System.out.println("current time in GMT: " + getTime(cal));
//adding hours into Date
cal.add(Calendar.HOUR_OF_DAY, 3);
System.out.println("Time after 3 hours : " + getTime(cal));
//subtracting hours from Date time
cal.add(Calendar.HOUR_OF_DAY, -3);
System.out.println("Time before 3 hours : " + getTime(cal));
//adding minutes into Date time
cal.add(Calendar.MINUTE, 3);
System.out.println("Time after 3 minutes : " + getTime(cal));
//subtracting minutes from Date time
cal.add(Calendar.HOUR_OF_DAY, -3);
System.out.println("Time before 3 minuets : " + getTime(cal));
}
/**
*
* #return current Date from Calendar in dd/MM/yyyy format
* adding 1 into month because Calendar month starts from zero
*/
public static String getDate(Calendar cal){
return "" + cal.get(Calendar.DATE) +"/" +
(cal.get(Calendar.MONTH)+1) + "/" + cal.get(Calendar.YEAR);
}
/**
*
* #return current Date from Calendar in HH:mm:SS format
*
* adding 1 into month because Calendar month starts from zero
*/
public static String getTime(Calendar cal){
return "" + cal.get(Calendar.HOUR_OF_DAY) +":" +
(cal.get(Calendar.MINUTE)) + ":" + cal.get(Calendar.SECOND);
}
}
Sample Output Should be like this:
current date: 22/10/2019
date after 2 days : 22/10/2019
date before 2 days : 24/10/2019
date after 5 months : 22/3/2020
etc...
I know there are lots of questions on SO about how to get Dates in Java, but I want an example using new Java 8 Date API. I also know about the JodaTime library, but I want a method without relying on external libraries.
The function needs to be compliant with these restrictions:
Prevent errors from date savetime
Inputs are two Date objects (without time, I know about LocalDateTime, but I need to do this with Date instances)
If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:
LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);
If you want literal 24 hour days, (a duration), you can use the Duration class instead:
LocalDate today = LocalDate.now()
LocalDate yesterday = today.minusDays(1);
// Duration oneDay = Duration.between(today, yesterday); // throws an exception
Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option
For more information, refer to this document.
Based on VGR's comments here is what you can use:
ChronoUnit.DAYS.between(firstDate, secondDate)
You can use until:
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
LocalDate christmas = LocalDate.of(2014, Month.DECEMBER, 25);
System.out.println("Until christmas: " + independenceDay.until(christmas));
System.out.println("Until christmas (with crono): " + independenceDay.until(christmas, ChronoUnit.DAYS));
Output:
Until christmas: P5M21D
Until christmas (with crono): 174
As mentioned in a comment, if no unit is specified until returns Period.
Snippet from the documentation:
A date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'.
This class models a quantity or amount of time in terms of years, months, and days. See Duration for the time-based equivalent to this class.
DAYS.between
You can use DAYS.between from java.time.temporal.ChronoUnit
e.g.
import java.time.temporal.ChronoUnit;
...
long totalDaysBetween(LocalDate dateBefore, LocalDate dateAfter) {
return DAYS.between(dateBefore, dateAfter);
If startDate and endDate are instance of java.util.Date
We can use the between( ) method from ChronoUnit enum:
public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) {
//..
}
ChronoUnit.DAYS count days which completed 24 hours.
import java.time.temporal.ChronoUnit;
ChronoUnit.DAYS.between(startDate.toInstant(), endDate.toInstant());
//OR
ChronoUnit.DAYS.between(Instant.ofEpochMilli(startDate.getTime()), Instant.ofEpochMilli(endDate.getTime()));
Everyone is saying to use ChronoUnit.DAYS.between but that just delegates to another method you could call yourself. So you could also do firstDate.until(secondDate, ChronoUnit.DAYS).
The docs for both actually mention both approaches and say to use whichever one is more readable.
Use the DAYS in enum java.time.temporal.ChronoUnit . Below is the Sample Code :
Output :
*Number of days between the start date : 2015-03-01 and end date : 2016-03-03 is ==> 368.
**Number of days between the start date : 2016-03-03 and end date : 2015-03-01 is ==> -368*
package com.bitiknow.date;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
/**
*
* #author pradeep
*
*/
public class LocalDateTimeTry {
public static void main(String[] args) {
// Date in String format.
String dateString = "2015-03-01";
// Converting date to Java8 Local date
LocalDate startDate = LocalDate.parse(dateString);
LocalDate endtDate = LocalDate.now();
// Range = End date - Start date
Long range = ChronoUnit.DAYS.between(startDate, endtDate);
System.out.println("Number of days between the start date : " + dateString + " and end date : " + endtDate
+ " is ==> " + range);
range = ChronoUnit.DAYS.between(endtDate, startDate);
System.out.println("Number of days between the start date : " + endtDate + " and end date : " + dateString
+ " is ==> " + range);
}
}
Get number of days before Christmas from current day , try this
System.out.println(ChronoUnit.DAYS.between(LocalDate.now(),LocalDate.of(Year.now().getValue(), Month.DECEMBER, 25)));
Here you go:
public class DemoDate {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 1 month to the current date
LocalDate date2 = today.plus(1, ChronoUnit.MONTHS);
System.out.println("Next month: " + date2);
// Put latest date 1st and old date 2nd in 'between' method to get -ve date difference
long daysNegative = ChronoUnit.DAYS.between(date2, today);
System.out.println("Days : "+daysNegative);
// Put old date 1st and new date 2nd in 'between' method to get +ve date difference
long datePositive = ChronoUnit.DAYS.between(today, date2);
System.out.println("Days : "+datePositive);
}
}
get days between two dates date is instance of java.util.Date
public static long daysBetweenTwoDates(Date dateFrom, Date dateTo) {
return DAYS.between(Instant.ofEpochMilli(dateFrom.getTime()), Instant.ofEpochMilli(dateTo.getTime()));
}
If the goal is just to get the difference in days and since the above answers mention about delegate methods would like to point out that once can also simply use -
public long daysInBetween(java.time.LocalDate startDate, java.time.LocalDate endDate) {
// Check for null values here
return endDate.toEpochDay() - startDate.toEpochDay();
}
I know this question is for Java 8, but with Java 9 you could use:
public static List<LocalDate> getDatesBetween(LocalDate startDate, LocalDate endDate) {
return startDate.datesUntil(endDate)
.collect(Collectors.toList());
}
Use the class or method that best meets your needs:
the Duration class,
Period class,
or the ChronoUnit.between method.
A Duration measures an amount of time using time-based values (seconds, nanoseconds).
A Period uses date-based values (years, months, days).
The ChronoUnit.between method is useful when you want to measure an amount of time in a single unit of time only, such as days or seconds.
https://docs.oracle.com/javase/tutorial/datetime/iso/period.html
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
LocalDate dateBefore = LocalDate.of(2020, 05, 20);
LocalDate dateAfter = LocalDate.now();
long daysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter);
long monthsBetween= ChronoUnit.MONTHS.between(dateBefore, dateAfter);
long yearsBetween= ChronoUnit.YEARS.between(dateBefore, dateAfter);
System.out.println(daysBetween);
I was trying to compute week of year from a ISO-8601 Date format String input. Initially I tried this with java.time.ZonedDateTime but it gives incorrect result for Input Date - 2-Jan-2049. Then I tried with Calendar API it also gives incorrect response for 31-Dec-2049.
I have attached the sample test code
public class ZonedDateTimeTest {
public static void main(String[] args) throws InterruptedException {
System.out.println("======================================");
String instantStr1 = "2049-01-02T03:48:00Z";
printYearAndWeekOfYear(instantStr1);
System.out.println("======================================");
String instantStr2 = "2049-12-31T03:48:00Z";
printYearAndWeekOfYear(instantStr2);
System.out.println("======================================");
}
public static void printYearAndWeekOfYear(String ISODate) {
System.out.println("Date provided -> " + ISODate);
ZonedDateTime utcTimestamp = parseToInstant(ISODate).atZone(ZoneOffset.UTC);
int year = utcTimestamp.getYear();
int weekOfYear = utcTimestamp.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
System.out.println("Using ZonedDateTime API:: Year " + year + " weekOfYear " + weekOfYear);
Date d1 = Date.from(parseToInstant(ISODate));
Calendar cl = Calendar.getInstance();
cl.setTime(d1);
int year1 = cl.get(Calendar.YEAR);
int weekOfYear1 = cl.get(Calendar.WEEK_OF_YEAR);
System.out.println("Using Calendar API:: Year " + year1 + " weekOfYear " + weekOfYear1);
}
public static Instant parseToInstant(String ISODate) {
return DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(ISODate, Instant::from);
}
}
Output from code above
======================================
Date provided 2049-01-02T03:48:00Z
Using ZonedDateTime API: Year 2049 weekOfYear 53
Using Calendar API: Year 2049 weekOfYear 1
======================================
Date provided 2049-12-31T03:48:00Z
Using ZonedDateTime API: Year 2049 weekOfYear 52
Using Calendar API: Year 2049 weekOfYear 1
======================================
There are four problems with your code to start with:
You're using the system default time zone when you use Calendar, which may well change which date the Instant falls on. If you set the calendar to use UTC you'll make it more consistent.
You're using Calendar.YEAR which will give you the calendar year rather than the week year. You need to use Calendar.getWeekYear() instead.
You're using ZonedDateTime.getYear() which is again the calendar year. You shuold be using utcTimestamp.get(IsoFields.WEEK_BASED_YEAR)
You're using Calendar.getInstance() which could give you a non-Gregorian calendar, or it could have first-day-of-week set inappropriately for the computation you want to perform
Fixing these issues (and naming conventions) we end up with:
import java.util.*;
import java.time.*;
import java.time.format.*;
import java.time.chrono.*;
import java.time.temporal.*;
public class ZonedDateTimeTest {
public static void main(String[] args) {
printYearAndWeekOfYear("2049-01-02T03:48:00Z");
String instantStr2 = "2049-12-31T03:48:00Z";
printYearAndWeekOfYear("2049-12-31T03:48:00Z");
}
public static void printYearAndWeekOfYear(String isoDate) {
System.out.println("Date provided -> " + isoDate);
Instant instant = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(isoDate, Instant::from);
ZonedDateTime utcTimestamp = instant.atZone(ZoneOffset.UTC);
int year = utcTimestamp.get(IsoFields.WEEK_BASED_YEAR);
int weekOfYear = utcTimestamp.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
System.out.println("ZonedDateTime: Year " + year + " weekOfYear " + weekOfYear);
// Force the Gregorian calendar with ISO rules and using UTC
Calendar calendar = new GregorianCalendar();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setMinimalDaysInFirstWeek(4);
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(Date.from(instant));
int calYear = calendar.getWeekYear();
int calWeekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
System.out.println("Calendar: Year " + calYear + " weekOfYear " + calWeekOfYear);
System.out.println();
}
}
Output:
Date provided -> 2049-01-02T03:48:00Z
ZonedDateTime: Year 2048 weekOfYear 53
Calendar: Year 2048 weekOfYear 53
Date provided -> 2049-12-31T03:48:00Z
ZonedDateTime: Year 2049 weekOfYear 52
Calendar: Year 2049 weekOfYear 52
Both of those look good to me.
The old Calendar-stuff indeed enables a solution since Java-7 so I show it as supplement to the Java-8-related answer of Jon Skeet:
String instantStr1 = "2049-01-02T03:48:00Z";
String instantStr2 = "2049-12-31T03:48:00Z";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date d1 = sdf.parse(instantStr1);
Date d2 = sdf.parse(instantStr2);
GregorianCalendar gcal = new GregorianCalendar();
gcal.setFirstDayOfWeek(Calendar.MONDAY);
gcal.setMinimalDaysInFirstWeek(4);
gcal.setTime(d1);
System.out.println(
"Using Calendar API: Year " + gcal.getWeekYear() + " weekOfYear "
+ gcal.get(Calendar.WEEK_OF_YEAR)
); // Using Calendar API: Year 2048 weekOfYear 53
gcal.setTime(d2);
System.out.println(
"Using Calendar API: Year " + gcal.getWeekYear() + " weekOfYear "
+ gcal.get(Calendar.WEEK_OF_YEAR)
); // Using Calendar API: Year 2049 weekOfYear 52
For Android-users where this API is standard: The method getWeekYear() is available since API-level 24.
I have two dates in String format like below -
String startDate = "2014/09/12 00:00";
String endDate = "2014/09/13 00:00";
I want to make sure startDate should be less than endDate. startDate should not be greater than endDate.
How can I compare these two dates and return boolean accordingly?
Convert them to an actual Date object, then call before.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd h:m");
System.out.println(sdf.parse(startDate).before(sdf.parse(endDate)));
Recall that parse will throw a ParseException, so you should either catch it in this code block, or declare it to be thrown as part of your method signature.
tl;dr
Use modern java.time classes to parse the inputs into LocalDateTime objects by defining a formatting pattern with DateTimeFormatter, and comparing by calling isBefore.
java.time
The modern approach uses the java.time classes.
Define a formatting pattern to match your inputs.
Parse as LocalDateTime objects, as your inputs lack an indicator of time zone or offset-from-UTC.
String startInput = "2014/09/12 00:00";
String stopInput = "2014/09/13 00:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu/MM/dd HH:mm" );
LocalDateTime start = LocalDateTime.parse( startInput , f ) ;
LocalDateTime stop = LocalDateTime.parse( stopInput , f ) ;
boolean isBefore = start.isBefore( stop ) ;
Dump to console.
System.out.println( start + " is before " + stop + " = " + isBefore );
See this code run live at IdeOne.com.
2014-09-12T00:00 is before 2014-09-13T00:00 = true
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Here is a fully working demo. For date formatting, refer - http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Dating {
public static void main(String[] args) {
String startDate = "2014/09/12 00:00";
String endDate = "2014/09/13 00:00";
try {
Date start = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH)
.parse(startDate);
Date end = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH)
.parse(endDate);
System.out.println(start);
System.out.println(end);
if (start.compareTo(end) > 0) {
System.out.println("start is after end");
} else if (start.compareTo(end) < 0) {
System.out.println("start is before end");
} else if (start.compareTo(end) == 0) {
System.out.println("start is equal to end");
} else {
System.out.println("Something weird happened...");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Use SimpleDateFormat to convert to Date to compare:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
Date start = sdf.parse(startDate);
Date end = sdf.parse(endDate);
System.out.println(start.before(end));
The simplest and safest way would probably be to parse both of these strings as dates, and compare them. You can convert to a date using a SimpleDateFormat, use the before or after method on the date object to compare them.
I think it could be done much simpler,
Using Joda Time
You can try parsing this dates simply:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm");
DateTime d1 = formatter.parseDateTime(startDate);
DateTime d2 = formatter.parseDateTime(endDate);
Assert.assertTrue(d1.isBefore(d2));
Assert.assertTrue(d2.isAfter(d1));
Use SimpleDateFormat to parse your string representation into instance of Date. The invoke getTime() to get milliseconds. Then compare the milliseconds.
public class DateComparision
{
public static void main(String args[]) throws AssertionError, ParseException
{
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
//comparing date using compareTo method in Java
System.out.println("Comparing two Date in Java using CompareTo method");
compareDatesByCompareTo(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
compareDatesByCompareTo(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
compareDatesByCompareTo(df, df.parse("02-03-2012"), df.parse("01-02-2012"));
//comparing dates in java using Date.before, Date.after and Date.equals
System.out.println("Comparing two Date in Java using Date's before, after and equals method");
compareDatesByDateMethods(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
compareDatesByDateMethods(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
compareDatesByDateMethods(df, df.parse("02-03-2012"), df.parse("01-02-2012"));
//comparing dates in java using Calendar.before(), Calendar.after and Calendar.equals()
System.out.println("Comparing two Date in Java using Calendar's before, after and equals method");
compareDatesByCalendarMethods(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
compareDatesByCalendarMethods(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
compareDatesByCalendarMethods(df, df.parse("02-03-2012"), df.parse("01-02-2012"));
}
public static void compareDatesByCompareTo(DateFormat df, Date oldDate, Date newDate)
{
//how to check if date1 is equal to date2
if (oldDate.compareTo(newDate) == 0)
{
System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
}
//checking if date1 is less than date 2
if (oldDate.compareTo(newDate) < 0)
{
System.out.println(df.format(oldDate) + " is less than " + df.format(newDate));
}
//how to check if date1 is greater than date2 in java
if (oldDate.compareTo(newDate) > 0)
{
System.out.println(df.format(oldDate) + " is greater than " + df.format(newDate));
}
}
public static void compareDatesByDateMethods(DateFormat df, Date oldDate, Date newDate)
{
//how to check if two dates are equals in java
if (oldDate.equals(newDate))
{
System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
}
//checking if date1 comes before date2
if (oldDate.before(newDate))
{
System.out.println(df.format(oldDate) + " comes before " + df.format(newDate));
}
//checking if date1 comes after date2
if (oldDate.after(newDate))
{
System.out.println(df.format(oldDate) + " comes after " + df.format(newDate));
}
}
public static void compareDatesByCalendarMethods(DateFormat df, Date oldDate, Date newDate)
{
//creating calendar instances for date comparision
Calendar oldCal = Calendar.getInstance();
Calendar newCal = Calendar.getInstance();
oldCal.setTime(oldDate);
newCal.setTime(newDate);
//how to check if two dates are equals in java using Calendar
if (oldCal.equals(newCal))
{
System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
}
//how to check if one date comes before another using Calendar
if (oldCal.before(newCal))
{
System.out.println(df.format(oldDate) + " comes before " + df.format(newDate));
}
//how to check if one date comes after another using Calendar
if (oldCal.after(newCal))
{
System.out.println(df.format(oldDate) + " comes after " + df.format(newDate));
}
}
}
OUTPUT
Comparing two Date in Java using CompareTo method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 is less than 04-05-2012
02-03-2012 is greater than 01-02-2012
Comparing two Date in Java using Date's before, after and equals method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 comes before 04-05-2012
02-03-2012 comes after 01-02-2012
Comparing two Date in Java using Calendar's before, after and equals method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 comes before 04-05-2012
02-03-2012 comes after 01-02-2012
I know the week number of the year, a week is start from Sunday, then Monday, Tuesday...,Saturday.
Since I know the week number, what's the efficient way to get the dates of the specific week by using Java code??
If you don't want external library, just use calendar.
SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, 23);
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println(sdf.format(cal.getTime()));
Pure Java 8 / java.time solution
Based on this:
final long calendarWeek = 34;
LocalDate desiredDate = LocalDate.now()
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, calendarWeek)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
You can use the joda time library
int weekNumber = 10;
DateTime weekStartDate = new DateTime().withWeekOfWeekyear(weekNumber);
DateTime weekEndDate = new DateTime().withWeekOfWeekyear(weekNumber + 1);
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution:
The first step is to find the first day of the week and as the second step, we just need to iterate all the seven days starting with this date.
Note that the first day of the week is Locale-dependent e.g. it is Monday in the UK while Sunday in the US. As per the ISO 8601 standards, it is Monday. For comparison, check the US calendar and the UK calendar.
Demo of the first step:
import java.time.LocalDate;
import java.time.Year;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
int weekNumber = 34;
System.out.println(getFirstDayOfWeek(weekNumber, Locale.UK));
System.out.println(getFirstDayOfWeek(weekNumber, Locale.US));
}
static LocalDate getFirstDayOfWeek(int weekNumber, Locale locale) {
return LocalDate
.of(Year.now().getValue(), 2, 1)
.with(WeekFields.of(locale).getFirstDayOfWeek())
.with(WeekFields.of(locale).weekOfWeekBasedYear(), weekNumber);
}
}
Output:
2021-08-23
2021-08-15
ONLINE DEMO
Demo of the second step:
import java.time.LocalDate;
import java.time.Year;
import java.time.temporal.WeekFields;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
// Test
getAllDaysOfTheWeek(34, Locale.US).forEach(System.out::println);
}
static LocalDate getFirstDayOfWeek(int weekNumber, Locale locale) {
return LocalDate
.of(Year.now().getValue(), 2, 1)
.with(WeekFields.of(locale).getFirstDayOfWeek())
.with(WeekFields.of(locale).weekOfWeekBasedYear(), weekNumber);
}
static List<LocalDate> getAllDaysOfTheWeek(int weekNumber, Locale locale) {
LocalDate firstDayOfWeek = getFirstDayOfWeek(weekNumber, locale);
return IntStream
.rangeClosed(0, 6)
.mapToObj(i -> firstDayOfWeek.plusDays(i))
.collect(Collectors.toList());
}
}
Output:
2021-08-15
2021-08-16
2021-08-17
2021-08-18
2021-08-19
2021-08-20
2021-08-21
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
You did not mention what return type do you exactly need but this code should prove useful to you. sysouts and formatter are just to show you the result.
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.WEEK_OF_YEAR, 30);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println(formatter.format(cal.getTime()));
cal.add(Calendar.DAY_OF_WEEK, 6);
System.out.println(formatter.format(cal.getTime()));
This answer is pretty much same as others. But, here it goes:
int year = 2018;
int week = 27;
int day = 1; //assuming week starts from sunday
Calendar calendar = Calendar.getInstance();
calendar.setWeekDate(year, week, day);
System.out.println(calendar.getTime());
for(int i=1; i<=7; i++) {
if(i <= 3) {
LocalDate desiredDate = LocalDate.now()
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 26)
.with(TemporalAdjusters.previousOrSame(DayOfWeek.of(i)));
System.out.println(desiredDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
} else {
LocalDate desiredDate = LocalDate.now()
.with(IsoFields.WEEK_OF_WEEK_BASED_YEAR, 26)
.with(TemporalAdjusters.nextOrSame(DayOfWeek.of(i)));
System.out.println(desiredDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
}
}
This snippet provides dates starting from monday to sunday based on the given week number
output:
28/06/2021
29/06/2021
30/06/2021
01/07/2021
02/07/2021
03/07/2021
04/07/2021
To verify check https://www.epochconverter.com/weeks/2021