Home > other >  change the time interval in spring app using the code
change the time interval in spring app using the code

Time:02-07

I have a spring boot applicate that is using many types of date objects it like:

  • java.util.Date
  • java.time.LocalDate
  • java.time.Instant

I have a sandbox environment, I want to do some tests on it, but in tests, I need time to be changed by shifting the current_time by one year, in other words, I want to interval the time by 1 year.

example: let's suppose the date now is 7/feb/2022 if I called any date function, I need it to return 7/feb/2023,

I want to change the date just in the spring app, I don't want to change the whole server time.

Is this doable in spring app for any of the previous date objects?


update: I am using code like this in all my app

LocalDate localDate = LocalDate.now();
Date date = new Date()

I don't want to change the code in all my app (line by line)

I am looking at changing the date by adding some configurations, not by changing the existing code.

CodePudding user response:

For java.time classes, you can pass an optional Clock argument. The Clock class offers several static method returning alerted clock behavior. One of those supports a fixed moment, that does not increment.

Set up your altered clock.

ZoneId zoneId = ZoneId.of( "Africa/Tunis" ) ;
LocalDate aYearFromToday = LocalDate.now( zoneId ).plusYears( 1 ) ;
ZonedDateTime zdt = aYearFromToday.atStartOfDay( zoneId ) ;
Instant instant = zdt.toInstant() ; 
Clock fixedClock = Clock.fixed( instant , zoneId ) ;

Usage.

Instant nowFake = Instant.now( fixedClock ) ;
LocalDate todayFake = LocalDate.now( fixedClock ) ;

CodePudding user response:

Most of these java objects work well with each other. I'm assuming you are storing the server time in one of these classes. There is a simple function to add a year in LocalDate. Here is what I would do to get one year after the given server time.

LocalDate serverDate = LocalDate.of(2022, 2, 7);
System.out.println(serverDate);

LocalDate newTestDate = serverDate.plusYears(1);
System.out.println(newTestDate);


2022-02-07
2023-02-07

Most of these date objects can convert into the other object with a simple function. Hope this answers your question!

  •  Tags:  
  • Related