1

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.

Mihir Patel
  • 456
  • 7
  • 20

4 Answers4

3

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);
Nicola Gallazzi
  • 7,897
  • 6
  • 45
  • 64
  • 1
    Thank you for letting us know about this. +1 – gil.fernandes Jun 13 '18 at 07:37
  • 1
    Or if you prefer: `LocalDate.now().plusDays(2)`. Or `LocalDate.now(ZoneId.systemDefault()).plusDays(2)` to tell the reader we have chosen the device time zone consciously. May also want the same time zone for `now` and for `toEpochSecond`. – Ole V.V. Jun 13 '18 at 09:06
2

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;
}
gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
1

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);
olikaf
  • 591
  • 3
  • 11
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;
Mihir Patel
  • 456
  • 7
  • 20