Mihir Patel
Mihir Patel

Reputation: 486

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.

Upvotes: 1

Views: 537

Answers (4)

olikaf
olikaf

Reputation: 601

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);

Upvotes: 1

Nicola Gallazzi
Nicola Gallazzi

Reputation: 8705

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);

Upvotes: 3

Mihir Patel
Mihir Patel

Reputation: 486

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;

Upvotes: 0

gil.fernandes
gil.fernandes

Reputation: 14611

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;
}

Upvotes: 2

Related Questions