Getting days between current date and other date in Java [duplicate] - java

This question already has answers here:
Difference in days between two dates in Java?
(19 answers)
Closed 5 years ago.
I need a method which returns the difference in days between the current day and other any date, I have the following:
private long getDays(Date dateOp) {
Calendar feCurrent=Calendar.getInstance();
feCurrent.set(Calendar.HOUR_OF_DAY, 0);
feCurrent.set(Calendar.MINUTE, 0);
feCurrent.set(Calendar.SECOND, 0);
Calendar feAna=Calendar.getInstance();
feAna.setTime(dateOp);
feAna.set(Calendar.HOUR_OF_DAY, 0);
feAna.set(Calendar.MINUTE, 0);
feAna.set(Calendar.SECOND, 0);
feAna.getTime());
long timeDiff = Math.abs(feAna.getTime().getTime() - feCurrent.getTime().getTime());
return TimeUnit.MILLISECONDS.toDays(timeDiff);
}
The thing is I'm always getting one day less, for example, if the date as parameter is Octuber 16th 2017, the result will 3, but it's actually four, I debugged and the timeDiff for those dates is 345599395 , when converted to days is 3.999....
Does anyone have idea why it's not working.
By the way the date as parameter is load from a database, because if I tried with a main setting both dates it works.

You can use java.time components if you use Java 8
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
final class PeriodTest {
public static void main(String[] args) {
LocalDate now = LocalDate.of(2017, 4, 4); // 2017-04-04
LocalDate otherDate = LocalDate.of(2015, 10, 23); // 23-10-2015
long days = Math.abs(ChronoUnit.DAYS.between(otherDate, now));
System.out.println("Days = " + days);
}
}
Output
Days = 529
Pros:
you don't have to play with old Calendar object
you can convert java.util.Date to java.time.Instant with Date.toInstant() method to get it working with current example
Java 6 solution
For Java 6 you can use Joda-Time that was a precursor of Java 8 Time API.
import org.joda.time.Days;
import org.joda.time.LocalDate;
final class PeriodTest {
public static void main(String[] args) {
LocalDate now = LocalDate.parse("2017-04-04");
LocalDate otherDate = LocalDate.parse("2015-10-23");
int days = Math.abs(Days.daysBetween(now, otherDate).getDays());
System.out.println("Days = " + days);
}
}

Related

How to generate an array of Date objects in Kotlin?

I want to generate an array of date objects Kotlin style, from current day descending each 5 days programmatically:
{now, 5_days_ago, 10_days_ago, etc..}
private fun dateArray() : ArrayList<Date> {
val date = Date()
val date2 = Date(date.time - 432000000)
val date3 = Date(date2.time - 432000000)
val date4 = Date(date3.time - 432000000)
val date5 = Date(date4.time - 432000000)
val date6 = Date(date5.time - 432000000)
val date7 = Date(date6.time - 432000000)
val date8 = Date(date7.time - 432000000)
val date9 = Date(date8.time - 432000000)
val dateA = Date(date9.time - 432000000)
return arrayListOf(date, date2, date3, date4, date5, date6, date7, date8, date9, dateA)
}
This way is to much overheaded. I bet Kotlin offers an elegant way?
java.time
Here’s a simple pure Java solution. Like others I am recommending that you use java.time, the modern Java date and time API, for your date work.
Period step = Period.ofDays(-5);
int numberOfDates = 10;
Period totalPeriod = step.multipliedBy(numberOfDates);
LocalDate today = LocalDate.now(ZoneId.of("America/Rosario"));
List<LocalDate> dates = today.datesUntil(today.plus(totalPeriod), step)
.collect(Collectors.toList());
System.out.println(dates);
Output:
[2020-09-14, 2020-09-09, 2020-09-04, 2020-08-30, 2020-08-25,
2020-08-20, 2020-08-15, 2020-08-10, 2020-08-05, 2020-07-31]
I trust that you can translate to Kotlin and maybe even refine it further in Kotlin.
It’s not well documented that you may use the two-arg LocalDate.datesUntil() with a negative period, but at least it works on my Java 11.
Sorry to say, your solution in the question not only has more code than needed, it is also incorrect. Subtracting 432 000 000 milliseconds each time assumes that a day is always 24 hours. Because of summer time (DST) and other time anomalies a day may be 23 or 25 hours or something in between. By using LocalDate we are free of such issues. You may also use for example ZonedDateTime of LocalDateTime instead if you want to include time of day, they work fine across summer time transitions too.
Link: Oracle tutorial: Date Time explaining how to use java.time.
I recommend you switch from the outdated and error-prone java.util date-time API to the modern java.time date-time API. Learn more about the modern date-time API from Trail: Date Time. If your Android API level is still not compliant with Java8, check How to use ThreeTenABP in Android Project and Java 8+ APIs available through desugaring.
Do it as follows using the Java modern date-time API:
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(getPastDaysOnIntervalOf(10, 5));// 10 days in past at an interval of 5 days
System.out.println(getPastDaysOnIntervalOf(5, 10));// 5 days in past at an interval of 10 days
}
static List<LocalDate> getPastDaysOnIntervalOf(int times, int interval) {
// The list to be populated with the desired dates
List<LocalDate> list = new ArrayList<>();
// Today
LocalDate date = LocalDate.now();
for (int i = 1; i <= times; i++) {
list.add(date);
date = date.minusDays(interval);
}
// Return the populated list
return list;
}
}
Output:
[2020-09-14, 2020-09-09, 2020-09-04, 2020-08-30, 2020-08-25, 2020-08-20, 2020-08-15, 2020-08-10, 2020-08-05, 2020-07-31]
[2020-09-14, 2020-09-04, 2020-08-25, 2020-08-15, 2020-08-05]
Using legacy API:
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(getPastDaysOnIntervalOf(10, 5));// 10 days in past at an interval of 5 days
System.out.println(getPastDaysOnIntervalOf(5, 10));// 5 days in past at an interval of 10 days
}
static List<Date> getPastDaysOnIntervalOf(int times, int interval) {
// The list to be populated with the desired dates
List<Date> list = new ArrayList<>();
// Today
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
for (int i = 1; i <= times; i++) {
list.add(date);
cal.add(Calendar.DATE, -interval);
date = cal.getTime();
}
// Return the populated list
return list;
}
}

how can you combine date and sql time into a single date time in java? [duplicate]

This question already has answers here:
How to merge java.sql.Date and java.sql.Time to java.util.Date?
(3 answers)
Merge java.util.date with java.sql.Time
(7 answers)
Closed 2 years ago.
Using java Calendar how can you combine the start date, day and starttime?
For example:
If the start date is 9/8/2020. The day is 2 and the start time is 8:00 AM then how can we obtain a java date that is 9/9/2020 8:00 AM. Here is my unsuccessful attempt.
def startDateTime(Date startDate, int day, java.sql.Time startTime){
def date
date = Calendar.getInstance()
date.setTime(startDate)
//adding day. since day 1 is the first day we need to add day - 1
date.add(Calendar.DATE, day - 1)
// setting the time from startTime
date.setTimeInMillis(startTime.getTime())
return date.getTime()
}
Thanks for the help.
You are calling date.setTime(startDate) and date.setTimeInMillis(startTime.getTime()). 2nd method is overriding the time set in 1st method. You should create 2 separate instances of Calendar.
Here is how you can achieve this
Create separate Calendar instances for startDay and startTime
Construct a new Calendar object from separate Calendar objects created in #1 & add day as per requirement
Here is the complete code:
import java.sql.Time;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
public class ProofOfConcept {
public static void main(String[] args) {
int day = 2;
Time startTime = new Time(1, 1, 1);
Calendar timeCalendar = Calendar.getInstance();
timeCalendar.setTime(startTime);
Date startDate = new Date();
Calendar startDateCalendar = Calendar.getInstance();
startDateCalendar.setTime(startDate);
/* Only java 8 and above
LocalDateTime localDateTime = LocalDateTime.of(startDateCalendar.get(Calendar.YEAR), startDateCalendar.get(Calendar.MONTH) + 1, startDateCalendar.get(Calendar.DAY_OF_MONTH),
timeCalendar.get(Calendar.HOUR), timeCalendar.get(Calendar.MINUTE), timeCalendar.get(Calendar.SECOND));
localDateTime = localDateTime.plusDays(day);
System.out.println("localDateTime : " + localDateTime);
Date dateFromLocalDateTime = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
System.out.println("dateFromLocalDateTime : " + dateFromLocalDateTime);*/
Calendar result = Calendar.getInstance();
result.set(startDateCalendar.get(Calendar.YEAR), startDateCalendar.get(Calendar.MONTH), startDateCalendar.get(Calendar.DAY_OF_MONTH) + 2,
timeCalendar.get(Calendar.HOUR), timeCalendar.get(Calendar.MINUTE), timeCalendar.get(Calendar.SECOND));
Date date = result.getTime();
System.out.println("date : " + date);
}
}
Output:
date : Tue Sep 08 01:01:01 IST 2020
Note : I suggest using java.time.* packages over java.util.*. Why? Check this. But this is only available in java 8. (Though, you can use joda time in versions below 8).
Edit : Moving Ole V.V. 's comment to answer.
For Java 7, I suggest using java.time, the modern Java date and time API, through the backport, ThreeTen Backport.
static LocalDateTime startDateTime(Date startDate, int day, java.sql.Time startTime) {
LocalTime startLocalTime = DateTimeUtils.toLocalTime(startTime);
return DateTimeUtils.toInstant(startDate)
.atZone(ZoneId.systemDefault())
.toLocalDate()
.plusDays(day - 1)
.atTime(startLocalTime);
}

How to get the Date Of Birth given number of years months and days of a person in java

Given year, month and days of a person, need to get Date of Birth -
Example - 19 years 1 moth and 2 days
16-Sept-2010 (have calculated it manually, may not be accurate)
LocalDateTime.now().minusYears(years).minusMonths(months).minusDays(days)
I would go with java.time.LocalDate and java.time.Period class. Calling minus methods might not be optimal as it will create new object for every method invocation (classes like LocalDate, LocalDateTime are immutable) :
Period period = Period.of(19, 1, 2); //period of 19 years, 1 month, 2 days
LocalDate birthday = LocalDate.now().minus(period); // compute the birthday
String formattedDate = birthday.format(DateTimeFormatter.ofPattern("dd-MMMM-YYYY", Locale.UK));
System.out.println(formattedDate);
The output is :
15-September-2000
Basically, you can use the modern API for dates and times java.time and especially the class LocalDate. It has methods to add or subtract units of time, such as days, months and years.
public static void main(String[] args) {
System.out.println("Imagine someone being 19 years, 1 months and 2 days old today...");
LocalDate birthday = getBirthdayFromAge(19, 1, 2);
System.out.println("Then this person was born on "
+ birthday.format(DateTimeFormatter.ISO_DATE));
}
public static LocalDate getBirthdayFromAge(int years, int months, int days) {
return LocalDate.now()
.minusDays(days)
.minusMonths(months)
.minusYears(years);
}
This outputs
Imagine someone being 19 years, 1 months and 2 days old today...
Then this person was born on 2000-09-15
You should to transform year to Timestamp,month to Timestamp, day to Timestamp.
Diff this with current timestamp and you will get birth date Timestamp
Here is quick fix for you. Please check following code.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Birthdate {
public static void main(String[] args) {
Birthdate calUsage = new Birthdate();
calUsage.subtractTime();
}
private void subtractTime() {
Calendar calendar = new GregorianCalendar();
String pattern = "yyyy-MMMM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
String date = sdf.format(calendar.getTime());
System.out.println("Current Date::" + date);
calendar.add(Calendar.MONTH, -1);
calendar.add(Calendar.DAY_OF_YEAR, -2);
calendar.add(Calendar.YEAR, -19);
date = sdf.format(calendar.getTime());
System.out.println("Birthdate ::" + date);
}
}
Hope this solution works.

How to get the time difference in seconds? [duplicate]

This question already has answers here:
Java-How to calculate accurate time difference while using Joda Time Jar
(2 answers)
Closed 7 years ago.
I have used Jodha Library and tried to get the difference between two dates in seconds. But it is only accurate up to the date. Not to the seconds.
public static int getDateDifference(DateTime dateCreatedPa)
{
LocalDate dateCreated = new LocalDate (dateCreatedPa);
LocalDate now = new LocalDate();
Seconds secondsBetween = Seconds.secondsBetween(dateCreated, now);
return secondsBetween.getSeconds();
}
///code calling the above method
DateTime dateCreated=new DateTime(drivingLicense.getDateCreated());
int dateDiff=Common.getDateDifference(dateCreated);
request.setAttribute("dateDiff", dateDiff);
System.out.println("Timestamp: "+dateDiff);
This shows the date difference. But if I give different times on the same date for comparison, it returns 0.
LocalDate is just that, date only, no time information. Use LocalDateTime instead
import org.joda.time.DateTime;
import org.joda.time.LocalDateTime;
import org.joda.time.Seconds;
public class Test {
public static void main(String[] args) {
DateTime today = DateTime.now();
today = today.minusDays(5);
int dateDiff = getDateDifference(today);
System.out.println("Timestamp: " + dateDiff);
}
public static int getDateDifference(DateTime dateCreatedPa) {
LocalDateTime dateCreated = new LocalDateTime(dateCreatedPa);
LocalDateTime now = new LocalDateTime();
System.out.println(dateCreated);
System.out.println(now);
Seconds secondsBetween = Seconds.secondsBetween(dateCreated, now);
return secondsBetween.getSeconds();
}
}
Outputs...
2015-02-27T15:20:56.524
2015-03-04T15:20:56.628
Timestamp: 432000

java get the first date and last date of given month and given year [duplicate]

This question already has answers here:
How to get the first date and last date of the previous month? (Java)
(9 answers)
Closed 4 years ago.
I am trying to get the first date and the last date of the given month and year. I used the following code to get the last date in the format yyyyMMdd. But couldnot get this format. Also then I want the start date in the same format. I am still working on this. Can anyone help me in fixing the below code.
public static java.util.Date calculateMonthEndDate(int month, int year) {
int[] daysInAMonth = { 29, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day = daysInAMonth[month];
boolean isLeapYear = new GregorianCalendar().isLeapYear(year);
if (isLeapYear && month == 2) {
day++;
}
GregorianCalendar gc = new GregorianCalendar(year, month - 1, day);
java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());
return monthEndDate;
}
public static void main(String[] args) {
int month = 3;
int year = 2076;
final java.util.Date calculatedDate = calculateMonthEndDate(month, year);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
format.format(calculatedDate);
System.out.println("Calculated month end date : " + calculatedDate);
}
java.time.YearMonth methods atDay & atEndOfMonth
The java.time framework built into Java 8+ (Tutorial) has commands for this.
The aptly-named YearMonth class represents a month of a year, without any specific day or time. From there we can ask for the first and days of the month.
YearMonth yearMonth = YearMonth.of( 2015, 1 ); // 2015-01. January of 2015.
LocalDate firstOfMonth = yearMonth.atDay( 1 ); // 2015-01-01
LocalDate lastOfMonth = yearMonth.atEndOfMonth(); // 2015-01-31
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.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
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, and later
Built-in.
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
Much 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.
Simply you can use Calendar class. you should assign month variable which month you want
Calendar gc = new GregorianCalendar();
gc.set(Calendar.MONTH, month);
gc.set(Calendar.DAY_OF_MONTH, 1);
Date monthStart = gc.getTime();
gc.add(Calendar.MONTH, 1);
gc.add(Calendar.DAY_OF_MONTH, -1);
Date monthEnd = gc.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
System.out.println("Calculated month start date : " + format.format(monthStart));
System.out.println("Calculated month end date : " + format.format(monthEnd));
First day:
Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH);
Last day of month:
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
To get the Start Date
GregorianCalendar gc = new GregorianCalendar(year, month-1, 1);
java.util.Date monthEndDate = new java.util.Date(gc.getTime().getTime());
System.out.println(monthEndDate);
(Note : in the Start date the day =1)
for the formatted
SimpleDateFormat format = new SimpleDateFormat(/////////add your format here);
System.out.println("Calculated month end date : " + format.format(calculatedDate));
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
format.format(calculatedDate);
System.out.println("Calculated month end date : " + calculatedDate);
Change it to
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
String formattedDate = format.format(calculatedDate);
System.out.println("Calculated month end date : " + formattedDate);
For more detail
http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html#format(java.util.Date)
Another Approach
package com.shashi.mpoole;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateMagic {
public static String PATTERN = "yyyyMMdd";
static class Measure {
private int month;
private int year;
private Calendar calendar;
public Measure build() {
calendar = Calendar.getInstance();
calendar.set(year, month, 1);
return this;
}
public Measure(int year, int month) {
this.year(year);
this.month(month);
}
public String min() {
return format(calendar.getActualMinimum(Calendar.DATE));
}
public String max() {
return format(calendar.getActualMaximum(Calendar.DATE));
}
private Date date(GregorianCalendar c) {
return new java.util.Date(c.getTime().getTime());
}
private GregorianCalendar gc(int day) {
return new GregorianCalendar(year, month, day);
}
private String format(int day) {
SimpleDateFormat format = new SimpleDateFormat(PATTERN);
return format.format(date(gc(day)));
}
public void month(int month) {
this.month = month - 1;
}
public void year(int year) {
this.year = year;
}
}
public static void main(String[] args) {
Measure measure = new Measure(2020, 6).build();
System.out.println(measure.min());
System.out.println(measure.max());
}
}
Try below code for last day of month : -
Calendar c = Calendar.getInstance();
c.set(2012,3,1); //------>
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(sdf.format(c.getTime()));
http://www.coderanch.com/t/385759/java/java/date-date-month
Although, not exactly the answer for the OP question, below methods will given current month first & last dates as Java 8+ LocalDate instances.
public static LocalDate getCurrentMonthFirstDate() {
return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).withDayOfMonth(1);
}
public static LocalDate getCurrentMonthLastDate() {
return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).plusMonths(1).withDayOfMonth(1).minusDays(1);
}
Side note: Using LocalDate.ofEpochDay(...) instead of LocalDate.now() gives much improved performance. Also, using the millis-in-a-day expression instead of the end value, which is 86400000 is performing better. I initially thought the latter would perform better than the the expression :P
Why this answer: Even this is not a correct answer for OP question, I m still answering here as Google showed this question when I searched for 'java 8 get month start date' :)
GregorianCalendar gc = new GregorianCalendar(year, selectedMonth-1, 1);
java.util.Date monthStartDate = new java.util.Date(gc.getTime().getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(monthStartDate);
calendar.add(calendar.MONTH, 1);
calendar.add(calendar.DAY_OF_MONTH, -1);
java.util.Date monthEndDate = new java.util.Date(calendar.getTime())
public static Date[] getMonthInterval(Date data) throws Exception {
Date[] dates = new Date[2];
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.setTime(data);
start.set(Calendar.DAY_OF_MONTH, start.getActualMinimum(Calendar.DAY_OF_MONTH));
start.set(Calendar.HOUR_OF_DAY, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
end.setTime(data);
end.set(Calendar.DAY_OF_MONTH, end.getActualMaximum(Calendar.DAY_OF_MONTH));
end.set(Calendar.HOUR_OF_DAY, 23);
end.set(Calendar.MINUTE, 59);
end.set(Calendar.SECOND, 59);
//System.out.println("start "+ start.getTime());
//System.out.println("end "+ end.getTime());
dates[0] = start.getTime();
dates[1] = end.getTime();
return dates;
}

Categories

Resources