Calculate time difference between current and future time - java

I want to calculate time difference in milliseconds from current time of a day(11 am , 1 october,2012) and time at midnight for the same day (11 pm 59 m 59s , 1 october , 2012.
I have tried this
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 59);
cal.add(Calendar.HOUR, 23);
cal.add(Calendar.MINUTE, 59);
cal.getTime().getTime() - today.getTime();
here today is the current date.
But when i print long values of cal and today , the time difference if of 86400 approx one day.

Use cal.set() instead of cal.add()
Calendar cal = Calendar.getInstance();
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.HOUR, 23);
cal.set(Calendar.MINUTE, 59);
long diff = cal.getTime().getTime() - today.getTime();

You can set your date to newly created Calendar instance..
And then compare it with current instance using getTimeInMillis()
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.DATE, 1);
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.YEAR, 2012);
long difference = cal.getTimeInMillis() - Calendar.getInstance().getTimeInMillis();

Related

Set Calendar Date to Current Date

I have variable with value of timeInMills which is past 3 days ago, I wanted to reset the date of it to current date but the time should be still.
Calendar calNow = Calendar.getInstance();
Calendar calSets = (Calendar)calNow.clone();
calSets.setTimeInMillis(TIME_IN_MILL); //set datetime from timeInMillis
//Reset the date to current Date.
How to do that?
Like this, get the properties you want, before you change the instance:
Calendar calNow = Calendar.getInstance();
Calendar calSets = (Calendar)calNow.clone();
int hours = calNow.get(Calendar.HOUR_OF_DAY)
int minutes = calNow.get(Calendar.MINUTE)
calSets.setTimeInMillis(TIME_IN_MILL); //set datetime from timeInMillis
//Reset the date to current Date.
calSets.set(Calendar.SECOND, 0);
calSets.set(Calendar.MILLISECOND, 0);
calSets.set(Calendar.HOUR_OF_DAY, hours);
calSets.set(Calendar.MINUTE, minutes);
You can reset a Calendar by calling setTimeInMillis(System.currentTimeMillis()):
TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // Just for testing
final long TIME_IN_MILL = 1563204600000L; // 2019-07-15 15:30 UTC
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(TIME_IN_MILL);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
cal.setTimeInMillis(System.currentTimeMillis()); // Reset
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(cal.getTime()));
The code prints 2019-07-18 15:30:00.000, which is todays date with the time of day from the TIME_IN_MILL value.
If you don't want to rely on System.currentTimeMillis(), just get the value from the Calendar object, first thing:
Calendar cal = Calendar.getInstance();
long now = cal.getTimeInMillis();
cal.setTimeInMillis(TIME_IN_MILL);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
cal.setTimeInMillis(now);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

Get date-time in seconds from current date

Need to get date-time in seconds from current date.
Want to add 2 days from current date-time and get value of 7 PM of result day.
I.E.
Current date-time is 1 January, 7:05 PM OR 6:55 PM, I should get value of 3 January, 7:00 PM in seconds.
P.S. - Can't use JODA Time & Java 8.
Did you try ThreeTenABP by Jake Wharton? https://github.com/JakeWharton/ThreeTenABP. You can use it also for android versions before api 26 (required for the new java.time.instant) and it has all the functionalities of the Java 8 api.
I would do:
LocalDate myDate;
myDate = LocalDate.now().plus(2, ChronoUnit.DAYS);
LocalDateTime myDateAtTime = myDate.atTime(19,0,0);
long millis = myDateAtTime.toEpochSecond(ZoneOffset.UTC);
Without using Java 8 you can do something like this:
public static void main(String[] args) throws Throwable {
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, 2);
c.set(Calendar.HOUR_OF_DAY, 19);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
System.out.println(c.getTimeInMillis() / 1000L); // Time in seconds in two days at 7:00 pm
}
You could also create a static method for this:
private static long timeInTwoDaysAt7pm() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, 2);
c.set(Calendar.HOUR_OF_DAY, 19);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTimeInMillis() / 1000L;
}
If java 8 is a no go, then you can use Calendar :
import java.util.Calendar
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 2);
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Not sure if this is a correct approach or any better solution is there.
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 2);
c.set(Calendar.HOUR_OF_DAY, 19);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long timeInSeconds = c.getTime().getTime() / 100;

Java Calendar returns wrong month

I want store a date into a Calendar Object, like this:
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.set(Calendar.YEAR, 2017);
cal.set(Calendar.MONTH, Calendar.JUNE);
cal.set(Calendar.DAY_OF_YEAR, 26);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
All values are set correctly, except the month and if I call cal.getTime() it returns:
Thu Jan 26 10:00:00 CET 2017
What am I doing wrong?
When you use DAY_OF_YEAR you set the number day of the current year.
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#DAY_OF_YEAR
DAY_OF_YEAR Field number for get and set indicating the day number
within the current year.
This overrides all sensible configuration like month or year (to current year and month of the number day).
So instead of use DAY_OF_YEAR you may use DAY_OF_MONTH which seems is what you are looking for, this sets the day of the month you set before.
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#DAY_OF_MONTH
DAY_OF_MONTH Field number for get and set indicating the day of the month. This is a synonym for DATE. The first day of the month has value 1.
So the configuration you are looking for definetively seems it would be like next:
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.set(Calendar.YEAR, 2017);
cal.set(Calendar.MONTH, Calendar.JUNE);
cal.set(Calendar.DAY_OF_MONTH , 26);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Then when you call getTime you will get:
Mon Jun 26 11:00:00 CEST 2017
As mentioned in "Why Java Calendar set(int year, int month, int date) not returning correct date?" this is an easy way to initialize a Calendar Object.
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.set(2017, Calendar.JUNE, 26, 9, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(cal.getTime());
Mon Jun 26 11:00:00 CEST 2017

How in Java find dates for previous 2 mondays?

May be like this:
for(int i=0;i<15;i++){
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_MONTH, -1);
if (cal.Calendar.DAY_OF_WEEK==1){
System.out.println(cal.cal.getTime())
But may be exists more simple way?
Thanks.
You are on the right track.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -7); // First week before
cal.add(Calendar.DAY_OF_YEAR, -7); // Second week before
Let me make this work for just Mondays.
Calendar cal = Calendar.getInstance();
int weekday = cal.get(Calendar.DAY_OF_WEEK);
int days = (Calendar.SATURDAY - weekday + 2) % 7;
cal.add(Calendar.DAY_OF_YEAR, days);
cal.add(Calendar.DAY_OF_MONTH, -7);
cal.add(Calendar.DAY_OF_MONTH, -7);
Even simpler would be to set the weekday directly:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
cal.add(Calendar.DATE, -7);
System.out.println(cal.getTime());
Please keep in mind, that this does not effect the time. If you want 00:00, you need to set the appropriate values:
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
java.time
Use a TemporalAdjuster.
LocalDate today = LocalDate.now();
LocalDate previousOrSameMonday = today.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) );
And subtract a week to get a second one.
LocalDate secondMondayBefore = previousOrSameMonday.minusWeeks( 1 );

Composing and comparing a date in Java

I used this to create a date and put it into a database:
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
I want to build a date with a similar format to the one above and compare it with currentDateTimeString.
I have 3 integers. How do I do that (int year, int month, int day)?
UPDATE:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, month);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.DAY_OF_MONTH, day);
Date result = cal.getTime();
String currentDateTimeString2 = DateFormat.getDateInstance().format(result);
I do here something wrong..both arent equal:
currentDateTimeString2==currentDateTimeString //false
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, date);
cal.set(Calendar.MONTH, month-1);//it starts from 0
cal.set(Calendar.YEAR, year);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date result = cal.getTime();
I do here something wrong..both arent equal: currentDateTimeString2==currentDateTimeString //false
String are object, it can't be compared with == use equals() method
Dates are represented in milliseconds. new Date returns the current date, and by date it means year, month, day, hour, minute, second, millisecond.
Comparison can be made via Date.isAfter.
Don't use Strings to compare Dates. Don't use == to compare Objects.

Categories