Saurabh
Saurabh

Reputation: 43

Util class in java to output timestamp

I am new in java and I have a requirement where I need to create a method which has to output the timestamp for current datetime + 2 months. Basically in my code I have used the timestamp which is hardcoded and it is getting expired in evry 2 months so I want to replace the hardcode value with the output of a method which will calculate the timestamp of after 2 months from now and I can pass the output to my method instead of hardcoding. Can someone please help me with the utility to meet my requirement .

rules.add(CreateDiscountV8.createDiscountV8Rule(1564185600000l, 1640952000000l, 0, ruleEffectiveTimes, "P", "AC", "E", "AC", 0l, Long.MAX_VALUE, 0l, Long.MAX_VALUE,"bexdl", "x-in-y",null, 100, DEFAULT_MIN_TRIP_SEGMENTS, DEFAULT_MAX_TRIP_SEGMENTS, false, 1));

I am trying something like this but getting error in compiling it.

public class GetDynamicTimestamp {
    public static EndDateTimestamp getEndDate()
    {
        long currentTimestamp = System.currentTimeMillis();
        long enddatetimestamp = currentTimestamp + 200000000l;
        return enddatetimestamp;
    }
}

Upvotes: 2

Views: 160

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79395

Solution using java.time, the modern Date-Time API:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getEndDate());
    }

    public static long getEndDate() {
        return OffsetDateTime.now(ZoneOffset.UTC)
                .plusMonths(2)
                .toInstant()
                .toEpochMilli();
    }
}

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

What went wrong with your code

In your code, the return type of the function, getEndDate is EndDateTimestamp whereas you are returning a long value. Also, it's not a good idea to perform the calculations manually if there are specialized API to achieve the same.

Upvotes: 2

Related Questions