Subtracting 5 minutes from epoch date [duplicate] - java

This question already has answers here:
subtracting two days from current date in epoch milliseconds java [duplicate]
(5 answers)
Closed 8 years ago.
What is the best way to subtract 5 minutes from a given epoch date ?
public long fiveMinutesAgo(String epochDate) {
//ToDo
return fiveMinBack;
}

epochDate has to be a Date. Use a Calendar:
Calendar calendar = Calendar.getInstance();
calendar.setTime(epochDate);
calendar.add(Calendar.MINUTE, -5);
Date result = calendar.getTime();

You can use any of the above mentioned methods by other user , but if interested give a try to
Java 8 Date and Time API
public void subtract_minutes_from_date_in_java8 ()
{
LocalDateTime newYearsDay = LocalDateTime.of(2015, Month.JANUARY, 1, 0, 0);
LocalDateTime newYearsEve = newYearsDay.minusMinutes(1);// In your case use 5 here
java.time.format.DateTimeFormatter formatter =java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss S");
logger.info(newYearsDay.format(formatter));
logger.info(newYearsEve.format(formatter));
}
Output :
01/01/2015 00:00:00 CST
12/31/2014 23:59:00 CST
Class LocalDateTime is an immutable date-time object present in java.time package in Java 8 that represents a date-time, often viewed as year-month-day-hour-minute-second.
Below is the syntax of of() method used :
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute)
which obtains an instance of LocalDateTime from year, month, day, hour and minute, setting the second and nanosecond to zero.

You can subtract 5 minute equivalent of miiliseconds from date you get:-
//convert input string epochDate to Date object based on the format
long ms=date.getTime();
Date updatedDate=new Date(ms - (5 * 60000)); //60000 is 1 minute equivalent in milliseconds
return updatedDate.getTime();

Here's a body for your method:
private static final long FIVE_MINS_IN_MILLIS = 5 * 60 * 1000;
public long fiveMinutesAgo(String epochDate) throws ParseException {
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
long time = df.parse(epochDate).getTime();
return time - FIVE_MINS_IN_MILLIS;
}
The time is in millis-since-the-epoch, so to find out five minutes before you simply have to subtract 5 mins in milliseconds (5 * 60 * 1000).
I would suggest renaming the method to: fiveMinutesBefore() and perhaps breaking it into two methods: one for parsing string dates into times and the other for subtracting minutes from the time.
You might also consider using Joda-Time as it's much better designed (and thread-safer) than the standard Java date package.

Related

Why there is a difference between GregorianCalendar.getTimeInMillis() and GregorianCalendargetTimeInMillis(1970.01.01)) [duplicate]

This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Why is January month 0 in Java Calendar?
(18 answers)
Closed 3 years ago.
I have tried to compare to Dates the Birthdate and the Current date
and then I tried to get the age.
But the Current date Funtion begins with another Date than the given date
My Code:
GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
long ms = System.currentTimeMillis() - birthdate.getTimeInMillis();
double years = (((double)ms / 1000)/31536000) ;
System.out.print(years);
// years Shoud be 18 here but it returns 17.3
if (years > 18) {
// Code Block
}
else{
System.out.print("to Jung");
}
Check the Constructor on GregorianCalendar.
public GregorianCalendar(int year,
int month,
int dayOfMonth)
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
year - the value used to set the YEAR calendar field in the calendar.
month - the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g., 0 for January.
dayOfMonth - the value used to set the DAY_OF_MONTH calendar field in the calendar.
You are creating a July 20th date, which is coincidentally offset by a single month, or approximately 0.08 years.
LocalDate birthdate = LocalDate.of(2001,06,20);
LocalDate currentdate = LocalDate.now();
int years = Period.between(birthdate , currentdate).getYears();
if (years >= 18) {
// Code
} else {
System.out.print("Sie sind zu Jung");
}
It Worked like this but I must change the hole code because everything was written with the GeorgianCalender.
I couldn't tell you why exactly your code, which should technically work, doesn't: there seems to be inaccuracies (leap days?) in the Calendar, or I'm missing something. Thanks to Compass, I know that I was missing something: months are 0-indexed in the constructor for Gregorian Calendar. 06 is July.
However, you shouldn't compare dates like this. If you don't want to use any other library, you can do this:
GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
GregorianCalendar today = new GregorianCalendar();
birthdate.add(Calendar.YEAR, 18);
System.out.print(birthdate.getTime().after(today.getTime()));

Java 8 calculate months between two dates

NOTE THIS IS NOT A DUPLICATE OF EITHER OF THE FOLLOWING
Calculating the difference between two Java date instances
calculate months between two dates in java [duplicate]
I have two dates:
Start date: "2016-08-31"
End date: "2016-11-30"
Its 91 days duration between the above two dates, I expected my code to return 3 months duration, but the below methods only returned 2 months. Does anyone have a better suggestion? Or do you guys think this is a bug in Java 8? 91 days the duration only return 2 months.
Thank you very much for the help.
Method 1:
Period diff = Period.between(LocalDate.parse("2016-08-31"),
LocalDate.parse("2016-11-30"));
Method 2:
long daysBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2016-08-31"),
LocalDate.parse("2016-11-30"));
Method 3:
I tried to use Joda library instead of Java 8 APIs, it works. it loos will return 3, It looks like Java duration months calculation also used days value. But in my case, i cannot use the Joda at my project. So still looking for other solutions.
LocalDate dateBefore= LocalDate.parse("2016-08-31");
LocalDate dateAfter = LocalDate.parse("2016-11-30");
int months = Months.monthsBetween(dateBefore, dateAfter).getMonths();
System.out.println(months);
Since you don't care about the days in your case. You only want the number of month between two dates, use the documentation of the period to adapt the dates, it used the days as explain by Jacob. Simply set the days of both instance to the same value (the first day of the month)
Period diff = Period.between(
LocalDate.parse("2016-08-31").withDayOfMonth(1),
LocalDate.parse("2016-11-30").withDayOfMonth(1));
System.out.println(diff); //P3M
Same with the other solution :
long monthsBetween = ChronoUnit.MONTHS.between(
LocalDate.parse("2016-08-31").withDayOfMonth(1),
LocalDate.parse("2016-11-30").withDayOfMonth(1));
System.out.println(monthsBetween); //3
Edit from #Olivier Grégoire comment:
Instead of using a LocalDate and set the day to the first of the month, we can use YearMonth that doesn't use the unit of days.
long monthsBetween = ChronoUnit.MONTHS.between(
YearMonth.from(LocalDate.parse("2016-08-31")),
YearMonth.from(LocalDate.parse("2016-11-30"))
)
System.out.println(monthsBetween); //3
Since Java8:
ChronoUnit.MONTHS.between(startDate, endDate);
//Backward compatible with older Java
public static int monthsBetween(Date d1, Date d2){
if(d2==null || d1==null){
return -1;//Error
}
Calendar m_calendar=Calendar.getInstance();
m_calendar.setTime(d1);
int nMonth1=12*m_calendar.get(Calendar.YEAR)+m_calendar.get(Calendar.MONTH);
m_calendar.setTime(d2);
int nMonth2=12*m_calendar.get(Calendar.YEAR)+m_calendar.get(Calendar.MONTH);
return java.lang.Math.abs(nMonth2-nMonth1);
}
The documentation of Period#between states the following:
The start date is included, but the end date is not.
Furthermore:
A month is considered if the end day-of-month is greater than or equal to the start day-of-month.
Your end day-of-month 30 is not greater than or equal to your start day-of-month 31, so a third month is not considered.
Note the parameter names:
public static Period between​(LocalDate startDateInclusive, LocalDate endDateExclusive)
To return 3 months, you can increment the endDateExclusive by a single day.
In case you want stick to java.time.Period API
As per java.time.Period documentation
Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)
where
#param startDateInclusive the start date, inclusive, not null
#param endDateExclusive the end date, exclusive, not null
So it is better to adjust your implementation to make your end date inclusive and get your desired result
Period diff = Period.between(LocalDate.parse("2016-08-31"),
LocalDate.parse("2016-11-30").plusDays(1));
System.out.println("Months : " + diff.getMonths());
//Output -> Months : 3
You have to be careful, never use LocalDateTime to calculate months between two dates the result is weird and incorrect, always use LocalDate !
here's is some code to prove the above:
package stack.time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class TestMonthsDateTime {
public static void main(String[] args) {
/**------------------Date Time----------------------------*/
LocalDateTime t1 = LocalDateTime.now();
LocalDateTime t2 = LocalDateTime.now().minusMonths(3);
long dateTimeDiff = ChronoUnit.MONTHS.between(t2, t1);
System.out.println("diff dateTime : " + dateTimeDiff); // diff dateTime : 2
/**-------------------------Date----------------------------*/
LocalDate t3 = LocalDate.now();
LocalDate t4 = LocalDate.now().minusMonths(3);
long dateDiff = ChronoUnit.MONTHS.between(t4, t3);
System.out.println("diff date : " + dateDiff); // diff date : 3
}
}
My 2%
This example checks to see if the second date is the end of that month. If it is the end of that month and if the first date of month is greater than the second month date it will know it will need to add 1
LocalDate date1 = LocalDate.parse("2016-08-31");
LocalDate date2 = LocalDate.parse("2016-11-30");
long monthsBetween = ChronoUnit.MONTHS.between(
date1,
date2);
if (date1.isBefore(date2)
&& date2.getDayOfMonth() == date2.lengthOfMonth()
&& date1.getDayOfMonth() > date2.getDayOfMonth()) {
monthsBetween += 1;
}
After the short investigation, still not totally fix my question, But I used a dirty solution to avoid return the incorrect duration. At least, we can get the reasonable duration months.
private static long durationMonths(LocalDate dateBefore, LocalDate dateAfter) {
System.out.println(dateBefore+" "+dateAfter);
if (dateBefore.getDayOfMonth() > 28) {
dateBefore = dateBefore.minusDays(5);
} else if (dateAfter.getDayOfMonth() > 28) {
dateAfter = dateAfter.minusDays(5);
}
return ChronoUnit.MONTHS.between(dateBefore, dateAfter);
}
The Java API response is mathematically accurate according to the calendar. But you need a similar mechanism, such as rounding decimals, to get the number of months between dates that matches the human perception of the approximate number of months between two dates.
Period period = Period.between(LocalDate.parse("2016-08-31"), LocalDate.parse("2016-11-30"));
long months = period.toTotalMonths();
if (period.getDays() >= 15) {
months++;
}

Adding days to Epoch time [Java] [duplicate]

This question already has answers here:
Get java.util.Calendar from days since epoch
(3 answers)
Closed 6 years ago.
Epoch time is the number of milliseconds that have passed since 1st January 1970, so if i want to add x days to that time, it seems natural to add milliseconds equivalent to x days to get the result
Date date = new Date();
System.out.println(date);
// Adding 30 days to current time
long longDate = date.getTime() + 30*24*60*60*1000;
System.out.println(new Date(longDate));
it gives the following output
Mon Dec 26 06:07:19 GMT 2016
Tue Dec 06 13:04:32 GMT 2016
I know i can use Calendar class to solve this issue, but just wanted to understand about this behaviour
Its Because JVM is treating Value of multiplication 30*24*60*1000 as Int And multiplication result is out of range of Integer it will give result : -1702967296 intends of 2592000000 so its giving date smaller then current date
Try Below code :
public class Test {
public static void main(final String[] args) {
Date date = new Date();
System.out.println(date);
// Adding 30 days to current time
System.out.println(30 * 24 * 60 * 60 * 1000); // it will print -1702967296
long longDate = (date.getTime() + TimeUnit.DAYS.toMillis(30));
System.out.println(TimeUnit.DAYS.toMillis(30));
date = new Date(longDate);
System.out.println(date);
}
}
You're hitting integer overflow with your number. 30*24*60*60*1000 = 2,592,000,000, which is bigger than a signed, 32-bit integer can hold (2,147,483,647).
Use longs instead, by appending L onto any of the numbers: 1000L, for instance.
Note that if you want to deal with daylight savings time (to say nothing of leap seconds!), this still won't be enough. But if you're willing to assume that a day is always exactly 24 hours, using longs will fix your problem. (Time is a complicated thing, and I would suggest using a library like joda or Java 8's classes to handle it for you!)
Edit your code as follows:
long longDate = date.getTime() + 30*24*60*60*1000L;
It will work for sure.
Try this:
DateTime timePlusTwoDays = new DateTime().plusDays(days);
long longDate = timePlusTwoDays.getTime();
System.out.println(new Date(longDate));
Dateime class has:
public DateTime plusDays(int days) {
if (days == 0) {
return this;
}
long instant = getChronology().days().add(getMillis(), days);
return withMillis(instant);
}

Im trying to calculate the number off days between 2 date objects [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 8 years ago.
public static int countWeeks() {
// setting dates
Calendar calStart = GregorianCalendar.getInstance();
calStart.set(2014, 8, 30);
Date dateStart = calStart.getTime();
Date dateEnd = new Date();
// count days and weeks
int diffInDays = Days.daysBetween(new DateTime(dateStart), new DateTime(dateEnd)).getDays(); // int weekNumber = (int) diffInDays / 7;
return weekNumber;
}
I'm trying to calculate the number of days and weeks between today and last week but I always get -3 as weekNumber. I have no idea what i'm doing wrong.
Thanks in advance.
First, I will assume that
int weekNumber = (int) diffInDays / 7;
is not commented since otherwise you would get a compilation error.
Now, as explained in my comment, by doing
calStart.set(2014, 8, 30);
You are setting the date at the end of setember, not of august. So, it is 3 weeks ahead of now, so you get a -3. Use the Calendar constants.
calStart.set(2014, Calendar.AUGUST, 30);
You set the startdate to Sep. 30th because te month is zero bases!
See the documentation from java.util.Calendar:
public final void set(int year,
int month,
int date) Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH. Previous values of other calendar fields are
retained. If this is not desired, call clear() first. Parameters: year
- the value used to set the YEAR calendar field. month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0
for January. date - the value used to set the DAY_OF_MONTH calendar
field. See Also:
You are getting -3 as the weeknumber since you have commented that out so it showing some random value. Also note that 8 shows the September month not Aug since months are 0 based.
So if you are aiming at August month then you may try this:
calStart.set(2014, 7, 30);
^^-- This represents August month
If you are on Java 8 you can use the Java time API:
LocalDate start = LocalDate.of(2014, 8, 30);
LocalDate end = LocalDate.now();
long days = ChronoUnit.DAYS.between(start, end);
return (int) days / 7;

Time problem with this code

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class test {
/*
* Calculate the difference between two date/times *
*
*/
private static long dateDiff(Date toDate, Date fromDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(toDate);
long ms = cal.getTimeInMillis();
cal.setTime(fromDate);
ms -= cal.getTimeInMillis();
return ms;
}
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = sdf.parse("11:00:00");
d2 = sdf.parse("10:00:00");
} catch (Exception e) {
e.printStackTrace();
}
long result = dateDiff(d1, d2);
Date time = new Date(result);
System.out.println(time);
}
}
When I run it I get this result :
Thu Jan 01 02:00:00 CET 1970
I would expect 1 hour difference ?! again a problem with Timezone??
Any idea how I can fix it.
thx all
I don't know what you expect this to do, but what you are actually doing is outputting the date corresponding to one hour after midnight on Jan 1 1970, using the default timezone.
You seem to want to Date to represent a duration (i.e. a number of seconds). It doesn't do that, and neither will the Date formatters render a Date as a duration.
I need the time difference between two Date fields and then put it in MySql (time format)
For what you are trying to do, you need calculate the duration value as a long, then use the java.sql.Time(long) constructor to create a Time object. You can either serialize this object using its toString() method or use it as a parameter in a JDBC prepared statement.
It turns out that my advice above is incorrect too.
Your real problem is that the SQL Time type is for representing times ... not durations. In fact, SQL does not have a dedicated duration type, so the best you can do is represent the duration as an integer number of seconds or milliseconds or whatever.
(For the more general case, the Joda Time libraries are generally thought to provide the best APIs for manipulating dates, times and related temporal values. But for this simple case, the standard J2SE libraries should suffice ... provided that you use them correctly.)
The problem is that a difference of two Date types can not be represented by another Date type.
Why don't you just take the milliseconds of both dates and substract them from each other?
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
long d1ms = cal.getTimeInMillis();
cal.setTime(d2);
long d2ms = cal.getTimeInMillis();
long diffMs = d1ms - d2ms;
long diffHour = diffMs * 1000 * 60 * 60;
Hi try this setting timezone to GMT. Remove day, month in words in the resultant time difference. This method does nothing but assumes these many milliseconds since starting of time counter in java, which is 1st Jan 1970. So if your result says 3rd Jan 1970 means 3 days have passed since time counter started, which is perfect. You just need to interpret it properly, but formatting your answer
...
long result = dateDiff(d1, d2); //This is your code in main([])
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss SSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormat.format(new Date(result )));

Categories

Resources