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
Related
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);
}
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.
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);
}
}
I have been trying to use the date.format(DateTimeFormatter formatter) method to format a list of date strings, where 'date' is a java.time.LocalDate object, for example. The problem is, I cannot find a straight-forward way to create a Year object from a string. For instance, if I have the string yearString = "90". I would like to create a Year object that is equal to this value, and then use the format method to output yearStringNew = "1990". The closest I see to a public constructor is the now() function which returns the current time.
I have also looked into creating a Calendar object and then creating a format-able date object there, but I can only create a Java.util.Date object – as opposed to an object in the Java.time package which could then ideally be formatted by the format function. Am I missing something here?
FYI I'm referencing the Java 8 SDK javadoc https://docs.oracle.com/javase/8/docs/api/
Thank you for your time.
EDIT: Per the request of another user, I have posted my code below; this is the closest I have come to accomplishing what I'm looking for:
//Module 3:
//Format Date Segments
package challenge245E;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
public class TestClass3 {
public static void main(String[] args) throws ParseException {
DateFormatter dateFormatter = new DateFormatter();
String myGroupedSlices [][] =
{
{"1990", "12", "06"},
{"12","6", "90"}
};
dateFormatter.formatDates(myGroupedSlices);
}
}
class DateFormatter {
public Date[][] formatDates(String[][] groupedDates) throws ParseException {
Date[][] formattedDates = new Date[groupedDates.length][3];
DateFormat yearFormat = new SimpleDateFormat("YYYY");
DateFormat monthFormat = new SimpleDateFormat("MM");
DateFormat dayFormat = new SimpleDateFormat("dd");
//iterate through each groupedSlices array
for (int i=0; i<groupedDates.length;i++) {
//Conditions
if (groupedDates[i][0].length()<3) {
//MDDYY format: if date[0].length < 3
//Re-arrange into YDM order
String m = groupedDates[i][0];
String y = groupedDates[i][2];
groupedDates[i][0] = y;
groupedDates[i][2] = m;
//convert dates to correct format
formattedDates[i][0] = yearFormat.parse(groupedDates[i][0]);
formattedDates[i][1] = monthFormat.parse(groupedDates[i][1]);
formattedDates[i][2] = dayFormat.parse(groupedDates[i][2]);
//testing if block
System.out.println("MDY Order: " + Arrays.toString(formattedDates[i]));
}
if (groupedDates[i][0].length()>3) {
//YYYYMMDD format: if date[0].length > 3
//convert dates to correct format
formattedDates[i][0] = yearFormat.parse(groupedDates[i][0]);
formattedDates[i][1] = monthFormat.parse(groupedDates[i][1]);
formattedDates[i][2] = dayFormat.parse(groupedDates[i][2]);
//testing if block
System.out.println("YMD Order: " + Arrays.toString(formattedDates[i]));
}
}
return formattedDates;
}
}
If I understand your requirement correctly, have a look at the LocalDate.parse() methods.
Example:
LocalDate date = LocalDate.parse("1990-01-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
int year = date.getYear(); // 1990
Parse Each Number Separately
It’s good to see you using the java.time framework rather than the troublesome old date-time classes. The old java.util.Date/.Calendar classes have been supplanted by the new framework.
The DateTimeFormatter class parses any two digit year as being in the 2000s. From class doc:
If the count of letters is two… will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.
To override this behavior, see this Answer by assylias. But that issue may be moot in your case. You already have the individual year, month, and date values isolated. So they need not be parsed together.
I suggest you convert each string into a integer. For the year, if less than 100 then add 1900.
String inputYear = "90";
String inputMonth = "12";
String inputDayOfMonth = "6";
int year = Integer.parseInt( inputYear );
int month = Integer.parseInt( inputMonth );
int dayOfMonth = Integer.parseInt( inputDayOfMonth );
if( year < 100 ) { // If two-digit year, assume the 1900s century. Even better: Never generate two-digit year text!
year = ( year + 1900 );
}
LocalDate localDate = LocalDate.of( year , month , dayOfMonth );
Create an Instance of class GregorianCalendar, set your date in that calendar and then use the method toZonedDateTime(). This will give you ZonedDateTime instance. form it you can use method LocalDate.from(TemporalAccessor temporal) method to get your LocalDate. Here how it might look:
//....
GregorianCalendar calendar = new GregorianCalendar();
// Set the deasired date in your calendar
LocalDate localDate = LocalDate.from(calendar.toZonedDateTime());
//...
import java.time.LocalDate;
public class DaysTilNextMonth {
public static void main(String[] args) {
//create an object for LocalDate class
LocalDate date = LocalDate.now();
//get today's day
int today = date.getDayOfMonth();
//get number of days in the current month
int numOfDaysInMonth = date.lengthOfMonth();
//compute the days left for next month
int dayForNextMonth = numOfDaysInMonth - today;
//display the result
System.out.println("The next month is: " + date.plusMonths(7).getMonth());
System.out.println("We have " + dayForNextMonth + " days left until first day of next month.");
}
}
This question already has answers here:
How do I measure time elapsed in Java? [duplicate]
(15 answers)
Closed 6 years ago.
Why the output of the Java code below is 04:18:23 and not 03:18:23?
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
try {
Date start = sdf.parse("00:44:16");
Date end = sdf.parse("04:02:39");
long duration = end.getTime() - start.getTime();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(duration);
System.out.println(sdf.format(cal.getTime()));
} catch (ParseException e) {
e.printStackTrace();
}
}
Because that's not how you get a duration. Change your code to this:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
try {
Date start = sdf.parse("00:44:16");
Date end = sdf.parse("04:02:39");
long duration = end.getTime() - start.getTime();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(duration);
System.out.println(new SimpleDateFormat("yyyy MM dd HH:mm:ss").format(cal.getTime()));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
You'll see it prints out 1969 12 31 19:18:23. That's a date not a duration. Since you're skipping the date components when you print out your answer, it appears like it's printing out a duration, but it's really not.
To be frank, I don't know how to do this in java. I just use the JodaTime library. There's a class called Duration that makes this easy. Here's a SO question that shows how to use it to print out the results any way you want: "pretty print" duration in java
Alternatively, if you don't want to use JodaTime, it's pretty simple to compute the hours, minutes, and seconds from a duration in milliseconds:
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date start = sdf.parse("00:44:16");
Date end = sdf.parse("04:02:39");
long durationMs = end.getTime() - start.getTime();
final int oneHourMs = 3600000;
final int oneMinuteMs = 60000;
final int oneSecondMs = 1000;
long hours = durationMs / oneHourMs;
long minutes = (durationMs % oneHourMs) / oneMinuteMs;
long seconds = (durationMs % oneMinuteMs) / oneSecondMs;
System.out.format("%02d:%02d:%02d", hours, minutes, seconds);
// outputs: 03:18:23
}
Problems:
You are cramming a time-of-day value into a date-time object.
You are using notoriously troublesome old date-time classes, now legacy, supplanted by the java.time classes.
The LocalTime class represents a time-of-day value without a date and without a time zone.
LocalTime start = LocalTime.parse( "00:44:16" );
LocalTime stop = LocalTime.parse( "04:02:39" );
The Duration represents a span of time not attached to the timeline.
Duration duration = Duration.between ( start , stop );